In the previous chapter we learn the command echo, this chapter we will introduce the command printf.
Printf mimics the printf () program in the C library.
Printf is defined by the POSIX standard, so scripts that use printf are more portable than echo.
Printf uses parameters which are text in quoted form or space-separated, format string can be used in printf outside, and the width and left-right alignment of the string can also be specified.By default, printf does not add line breaks automatically like echo, we can add \ n manually.
Name Gender Weight(kg)
Carol male 66.1234
Lily female 48.6543
Lucy female 47.9876
%s, %c,%d,%f are all format substitution characters
%-10s refers to a character with a width of 10 characters (-means left aligned, right means nothing), any character will be displayed within 10 characters wide, if not enough, it will be automatically filled with spaces, if exceeding, all content will be displayed.
%-4.2f means formatted as a decimal, where .2 means reserve 2 decimal places.
# format-string double quotes
printf "%d %s\n" 1 "abc"
# Single quotes have the same effect as double quotes
printf '%d %s\n' 1 "abc"
# Without quotes also can be output
printf %s abcdef
# The format only specifies one parameter, but the extra parameters will still be output in this format, format-string is reused
printf %s abc def
printf "%s\n" abc def
printf "%s %s %s\n" a b c d e f g h i j
# If there are no arguments, %s is replaced by NULL and %d is replaced by 0
printf "%s and %d \n"
Execute the script and output is
a b c
d e f
g h i
Printf escape sequence
alert (BEL),ASCII BEL character generally
produce no further output
character with octal value ddd (1 to 3 digits),only valid in format string
character with octal value ddd (1 to 3 digits)
$ printf "a string, no processing:<%s>\n" "A\nB"
a string, no processing:<A\nB>
$ printf "a string, no processing:<%b>\n" "A\nB"
a string, no processing:<A
$ printf "www.linuxcommands.site \a"
www.linuxcommands.site $ #Do not wrap