printf

The printf command, available in bash since version 2.02, has two parts (beyond the command name): a format string and a variable number of arguments:

printfformat-string [arguments]

format-string describes the format specifications; this is best supplied as a string constant in quotes. arguments is a 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 (see Table A-13).

Table A-13. printf format specifiers

Format character

Meaning

%c

ASCII character (prints first character of corresponding argument)

%d, %i

Decimal (base 10) integer

%e

Floating-point format ([-]d.precisione[+-]dd)—see the text after the table for the 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 shown in the table). 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, we put our format specifier between a pair of | in our format string so you can see the width of the field in the output. The first example right-justifies the text:

printf "|%10s|
" hello@

It produces:

|        hello|

The next example left-justifies the text:

printf "|%-10s|
" 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 even specify both the width and precision dynamically, via values in the printf argument list. You do this by specifying asterisks in the format expression, instead of literal values:

$ myvar=42.123456
$ mysig=6
$ printf "|%*.*G|
" 5 $mysig $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 and its exact meaning varies by control letter, as shown in Table A-14.

Table A-14. Meaning of “precision” based on printf format specifier

Format

What “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.

%b

[POSIX Shell—may be nonportable to other versions of printf.] When used instead of %s, expands echo-style escape sequences in the argument string (see Table A-15).

%q

[POSIX Shell—may be nonportable to other versions of printf.] When used instead of %s, prints the string argument in such a way that it can be used for shell input.

%b and %q are additions to bash (and other POSIX compliant shells) which 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. Here are two examples to make their functions a little clearer:

%q shell quotes:

$ printf "%q
" "greetings to the world"
greetings to the world

%b echo-style escapes:

$ printf "%s
" 'hello
world'
hello
world
$ printf "%b
" 'hello
world'
hello
world

Table A-15 shows the escape sequences that will be translated in a string printed with the %b format.

Table A-15. printf escape sequences

Escape sequence

Meaning

e

Escape character

a

Bell character



Backspace character

f

Form-feed character

Newline character

Carriage return character

Tab character

v

Vertical tab character

'

Single-quote character

Double-quote character

\

Backslash character

nn

8-bit character whose ASCII value is the 1, 2, or 3 digit octal number nnn

xHH

8-bit character whose ASCII value is the 1 or 2 digit hexadecimal number HH

Finally, one or more flags may precede the field width and the precision in a printf format specifier. We’ve already seen the -flag for left-justification. The rest of the flags are shown in Table A-16.

Table A-16. printf flags

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.

'

Format with thousands’ grouping characters if %i, %d, %u, %f, %F, %g, or %G (although this is POSIX, it’s still not always implemented).

Examples

These examples for printf use some shell variables, assigned as follows in Table A-17:

PI=3.141592653589

Table A-17. printf examples

printf statement

Result

Comment

printf '%f ' $PI

3.141593

Note the default rounding.

# not what you want printf '%f.5 ' $PI

3.14.5

A common mistake—the format specifier should be on the other side of the %f; since it isn’t, the .5 is just appended like any text.

printf '%.5f ' $PI

3.14159

Gives five places to the right of the decimal point.

printf '%+.2f ' $PI

+3.14

Leading + sign, only two digits to the right of the decimal point.

printf '[%.4s] ' s string

[s]

[stri]

Truncates to four characters; with only one character, we get only one character-wide output, note reuse of format string.

printf '[%4s] ' s string

[s]

[string]

Assures us of a minimum four-character field width, right-justified; doesn’t truncate, though.

printf '[%-4.4s] ' s string

[s]

[stri]

Does it all—minimum width of four, maximum width of four, truncating if necessary, and left justifies (due to the minus sign) shorter than four.

Here is one more example that will not display well in the table. The traditional way to write printf statements is to embed all formatting, including things like newlines, in the format string. This is shown in the table. That is encouraged, but you don’t have to do it that way, and sometimes it’s easier if you don’t. Note the →denotes a Tab character in the output:

$ printf "%b" "aRing terminal bell, then tab	 then newline
Then line 2.
"
Ring terminal bell, then tab → then newline
Then line 2.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.76.175