预计阅读本页时间:-
printf
bash 's echo command is quite powerful and for most cases entirely adequate. However, there are occasions where a more powerful and flexible approach is needed for printing information, especially when the information needs to be formatted. bash provides this by giving access to a powerful system-level printing library known as printf.[4]
The printf command can output a string similar to the echo command:
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
printf "hello world"
Unlike the echo command, printf does not automatically provide a newline. If we want to make it do the exactly same as a standard echo then we must provide one by adding \n to the end:
printf "hello world\n"
You may ask why this is any better than echo. The printf command has two parts, which is what makes it so powerful.
printf format-string [arguments]
The first part is a string that describes the format specifications; this is best supplied as a string constant in quotes. The second part is an argument list, such as a list of strings or variable values that correspond to the format specifications. (The format is reused as necessary to use up all of the arguments. If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied). A format specification is preceded by a percent sign (%), and the specifier is one of the characters described below. Two of the main format specifiers are %s for strings and %d for decimal integers.
This sounds complicated but we can begin by re-casting the last example:
printf "%s %s\n" hello world
This prints hello world on a line of its own, just as the previous example did. The word hello has been assigned to the first format specification, %s. Likewise, world has been assigned to the second %s. printf then prints these two strings followed by the newline.
We could also achieve the same result by making hello an explicit part of the format string:
$ printf "hello %s\n" world
hello world
The allowed specifiers are shown in Table 7-4.
Table 7-4. printf format specifiers
Specifier
Description
%c
ASCII character (prints first character of corresponding argument)
%d
Decimal integer
%i
Same as %d
%e
Floating-point format ([-]d.precisione[+-]dd) (see following text for meaning of precision)
%E
Floating-point format ([-]d.precisionE[+-]dd)
%f
Floating-point format ([-]ddd.precision)
%g
%e or %f conversion, whichever is shorter, with trailing zeros removed
%G
%E or %f conversion, whichever is shortest, with trailing zeros removed
%o
Unsigned octal value
%s
String
%u
Unsigned decimal value
%x
Unsigned hexadecimal number; uses a-f for 10 to 15
%X
Unsigned hexadecimal number; uses A-F for 10 to 15
%%
Literal %
The printf command can be used to specify the width and alignment of output fields. A format expression can take three optional modifiers following % and preceding the format specifier:
%flags width.precision format-specifier
The width of the output field is a numeric value. When you specify a field width, the contents of the field are right-justified by default. You must specify a flag of "-" to get left-justification. (The rest of the flags are discussed shortly.) Thus, "%-20s" outputs a left-justified string in a field 20 characters wide. If the string is less than 20 characters, the field is padded with whitespace to fill. In the following examples, a | is output to indicate the actual width of the field. The first example right-justifies the text:
printf "|%10s|\n" hello
It produces:
| hello|
The next example left-justifies the text:
printf "|%-10s|\n" hello
It produces:
|hello |
The precision modifier, used for decimal or floating-point values, controls the number of digits that appear in the result. For string values, it controls the maximum number of characters from the string that will be printed.
You can specify both the width and precision dynamically, via values in the printf argument list. You do this by specifying asterisks, instead of literal values.
$ myvar=42.123456
$ printf "|%*.*G|\n" 5 6 $myvar
|42.1235|
In this example, the width is 5, the precision is 6, and the value to print comes from the value of myvar.
The precision is optional. Its exact meaning varies by control letter, as shown in Table 7-5.
Table 7-5. Meaning of precision
Conversion
Precision means
%d, %I, %o, %u, %x, %X
The minimum number of digits to print. When the value has fewer digits, it is padded with leading zeros. The default precision is 1.
%e, %E
The minimum number of digits to print. When the value has fewer digits, it is padded with zeros after the decimal point. The default precision is 10. A precision of 0 inhibits printing of the decimal point.
%f
The number of digits to the right of the decimal point.
%g, %G
The maximum number of significant digits.
%s
The maximum number of characters to print.
Finally, one or more flags may precede the field width and the precision. We've already seen the "-" flag for left-justification. The rest of the flags are shown in Table 7-6.
Table 7-6. Flags for printf
Character
Description
-
Left-justify the formatted value within the field.
space
Prefix positive values with a space and negative values with a minus.
+
Always prefix numeric values with a sign, even if the value is positive.
#
Use an alternate form: %o has a preceding 0; %x and %X are prefixed with 0x and 0X, respectively; %e, %E and %f always have a decimal point in the result; and %g and %G do not have trailing zeros removed.
0
Pad output with zeros, not spaces. This only happens when the field width is wider than the converted result. In the C language, this flag applies to all output formats, even non-numeric ones. For bash, it only applies to the numeric formats.
If printf cannot perform a format conversion, it returns a non-zero exit status.
Additional bash printf specifiers
Besides the standard specifiers just described, the bash shell (and other POSIX compliant shells) accepts two additional specifiers. These provide useful features at the expense of nonportability to versions of the printf command found in some other shells and in other places in UNIX:
%b
When used instead of %s, expands echo-style escape sequences in the argument string. For example:
$ printf "%s\n" 'hello\nworld'
hello\nworld
$ printf "%b\n" 'hello\nworld'
hello
world
%q
When used instead of %s, prints the string argument in such a way that it can be used for shell input. For example:
$ printf "%q\n" "greetings to the world"
greetings\ to\ the\ world