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 already been described in the C-language getting Started tutorial, with features and usage similar to the printf command, see: C language Format output function printf () detailed
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:
Plain text Copy
- # 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 '
- $
Shell formatted output command printf