-----这里讲的printf指的是bash的内建命令(bash-builtin),而不是C函数中的printf(),不过它所实现的功能和printf()函数是非常类似的,可以说是echo命令的一个继承和发展,更加接近POSIX标准。
-----使用语法:
- printf
- SURNAME=china
- LASTNAME=unix
- printf "Surname: %snName:%sn" "$SURNAME" "$LASTNAME"
- Surname: china
- Name: unix
- printf -v var"%sxxx"
- echo $var
- xxx
一般情况下,ARGUMENT是一个字符(STRING),当然也可以是数值(字),不过有特定的格式,如下(为了尊重原“注”,这里给出英文注释):
| Number-Format | Description |
| N | A normal decimal number |
| 0N | An octal number |
| 0xN | A hexadecimal number |
| 0XN | A hexadecimal number |
| "X | (a literal double-quote infront of a character): interpreted asnumber (underlying codeset)don't forgetescaping |
| 'X | (a literal single-quote infront of a character): interpreted asnumber (underlying codeset)don't forgetescaping |
<1>如果FORMATspecifies少于ARGUMENTS的个数时,printf会按照设定好的格式,把所有的ARGUMENTS格式化输出。
例子:
- printf "%s#%s|n" "xxx""yyy" "zzz" "ttt" "vvv"
- xxx#yyy|
- zzz#ttt|
- vvv#|
例子:
- printf "%s#d#%sn""xxx"
- xxx#0000#
例子:
- printf "%dn""01"
- 1
- printf "%dn""08"
- -bash: printf: 08: invalidnumber
- 0
Printf对FORMAT的解释方法实质上和C函数的printf是一样的,它所识别的字符只有“diouxXfeEgGcs”,使用方法就百分号加上这些字符,”%+字符”。如果要打印百分号符,也很简单,double下,”%%”。
对以上“%+字符”的解释如下:
| Format | Description |
| %b | Print the associated argument while interpreting backslash escapesin there |
| %q | Print the associated argumentshell-quoted,reusable as input |
| %d | Print the associated argument assigneddecimalnumber |
| %i | Same as %d |
| %o | Print the associated argument asunsignedoctalnumber |
| %u | Print the associated argument asunsigneddecimalnumber |
| %x | Print the associated argument asunsignedhexadecimalnumber with lower-casehex-digits (a-f) |
| %X | Same as %x, but with upper-case hex-digits (A-F) |
| %f | Interpret and print the associated argumentasfloatingpointnumber |
| %e | Interpret the associated argument asdouble, and printit in ±e format |
| %E | Same as %e, but with an upper-case E in the printed format |
| %g | Interprets the associated argument asdouble, butprints it like %f or %e |
| %G | Same as %g, but print it like %E |
| %c | Interprets the associated argument as character: only the firstcharacter of a given argument is printed |
| %s | Interprets the associated argument literally as string |
| %b | Interprets the associated argument as a string and interpretingescape sequences in it |
| %q | Prints the associated argument in a format, that it can be re-usedas shell-input (escaped spaces etc..) |
| %n | No conversion or printing is done. Assigns the number of so farprinted characters to the variable named in the correspondingargument (similat to C's printf) |
| %(FORMAT)T | output the date-time string resulting from using FORMAT as a formatstring for strftime(3). The associated argument is the number ofseconds since Epoch, or -1 (current time) or -2 (shell startuptime) |
| %% | No conversion is done. Produces a % (percent sign) |
既然说printf,在功能上,是echo的继承和发展,那它就一定有更加flexible的设计,下面我们来例举一下。
<1> Modifiers (不知怎么翻译好)

先看个例子吧:
- printf "Psn" "This fieldis 50 characters wide..."
- This fieldis 50 characters wide...
下面让我们看看,还有什么其他的Modifiers:
Field outputformat | |
Anynumber: Specifies aminimum fieldwidth, if the text to print is smaller, it's padded withspaces, if the text is bigger, the field is expanded | |
. | Thedot: Together with a field width, the fieldisnotexpandedwhen the text is bigger, the text is cutted instead. "%.s" is anundocumented equivalent for "%.0s", which will force a field widthof zero, effectively hiding the field from output |
* | Theasterisk: the width is given as argument before the stringor number. Usage (the "*" corresponds to the "20"): printf "%*sn"20 "test string" |
# | "Alternative format" for numbers: see table below |
- | Left-boundtextprinting in the field (standard isright-bound) |
0 | Pads numbers with zeros, not spaces |
Pad a positive number with a space, where a minus (-) is fornegative numbers | |
+ | Prints all numberssigned(+for positive, - for negative) |
| AlternativeFormat | |
| %#o | The octal number is printed with a leading zero, unless it's zeroitself |
| %#x, %#X | The hex number is printed with a leading "0x"/"0X", unless it'szero |
| %#g, %#G | The float number is printed withtrailingzerosuntil the number of digits for thecurrent precision is reached (usually trailing zeros are notprinted) |
| all number formats except %d, %o, %x, %X | Always print a decimal point in the output, even if no digitsfollow it |
此外,精度(precision)也是常见的输出要求,格式为”.”,部分可以是具体的数字,也是”*”;如果是后者,写法上少有差异:
- printf "%.*fn" 104
- 4.0000000000
- printf "%.10fn"4
- 4.0000000000
下面是一些逃逸字符(Escape codes)的写法:
| Code | Description |
| \ | Prints the character (backslash) |
| a | Prints the alert character (ASCII code 7 decimal) |
| b | Prints a backspace |
| f | Prints a form-feed |
| n | Prints a newline |
| r | Prints a carriage-return |
| t | Prints a horizontal tabulator |
| v | Prints a vertical tabulator |
| " | Prints a ' |
| ? | Prints a ? |
| Interprets asoctalnumberand prints the corresponding character from the character set | |
爱华网