The printf command is used to format the output and is an enhanced version of the echo command. It is a finite variant of the C-language printf () library function, and is somewhat different in syntax.
Note: printf is defined by the POSIX standard, and portability is better than echo.
As with the echo command, the printf command can also output a simple string:
- $printf "Hello, Shell\ n"
- Hello, Shell
- $
printf does not wrap like echo, and you must explicitly add a line break (\ n).
The syntax of the printf command:
printf format-string [arguments ...]
Format-string is the format control string and arguments is the parameter list.
printf () has been described in the C-language introductory tutorial, features and usage similar to the printf command, see: C-Format output function printf ()
This is only a description of the difference from the C-language printf () function:
- printf command without parentheses
- Format-string can be without quotation marks, but it is best to add single quotes and double quotes.
- When the parameter is more than the format control (%), format-string can be reused and all parameters can be converted.
- Arguments use spaces separated by commas.
Take a look at the following example:
- # format-string is double quotes
- $ printf "%d%s\ n" 1 "abc"
- 1 ABC
- # single quotes are the same as double quotes
- $ printf '%d%s\ n' 1 "abc"
- 1 ABC
- # No quotation marks can also be output
- $ printf %s abcdef
- ABCdef
- # The format specifies only one parameter, but the extra parameter is still output in that format, format-string is reused
- $ printf %s ABC def
- ABCdef
- $ printf "%s\ n" abc def
- Abc
- Def
- $ printf "%s%s%s\ n" A b c D e F g h i j
- A b C
- D E F
- G h I
- J
- # If there is no arguments, then%s is replaced with NULL,%d replaces with 0
- $ printf "%s and%d \ n"
- and 0
- # If the string is displayed in%d format, then there will be a warning indicating an invalid number, at which point the default is 0
- $ printf "The first program always prints '%s,%d\ n'" Hello Shell
- -bash: printf: Shell: Invalid number
- The first program is always prints ' hello,0 '
- $
Note that, according to the POSIX standard, floating-point formats%E,%E,%f,%g, and%g are "No need to be supported." This is because awk supports floating-point budgeting and has its own printf statement. In this way, a small awk program can be used to print a floating-point value in a shell program. However, the printf commands built into bash, ksh93, and zsh support floating-point formatting.
Shell printf formatted output statement