Name

printf — stdin  stdout  - file  -- opt  --help  --version

Synopsis

printf format_string [arguments]

The printf command is an enhanced echo: it prints formatted strings on standard output. It operates much like the C programming language function printf( ), which applies a format string to a sequence of arguments to create some specified output. For example:

$ printf "User %s is %d years old.
" sandy 29
User sandy is 29 years old.

The first argument is the format string, which in our example contains two format specifications, %s and %d. The subsequent arguments, sandy and 29, are substituted by printf into the format string and then printed. Format specifications can get fancy with floating-point numbers:

$ printf "That'll be $%0.2f, sir.
" 3
That'll be $3.00, sir.

There are two printf commands available in Linux: one built into the bash shell, and one in /usr/bin/printf. The two are identical except for one format specification, %q, supported only by the bash built-in: it prints escape symbols (“”) so its output can be used as shell input safely. Note the difference:

$ printf "This is a quote: %s
" """
This is a quote: "
$ printf "This is a quote: %q
" """
This is a quote: "

It is your responsibility to make sure the number of format specifications (%) equals the number of arguments supplied to printf. If you have too many arguments, the extras are ignored, and if you have too few, printf assumes default values (0 for numeric formats, an empty string for string formats). Nevertheless, you should treat such mismatches as errors, even though printf is forgiving. If they lurk in your shell scripts, they are bugs waiting to happen.

Format specifications are described in detail on the manpage for the C function printf (see man 3 printf). Here are some useful ones.

%d

Decimal integer

%ld

Long decimal integer

%o

Octal integer

%x

Hexadecimal integer

%f

Floating point

%lf

Double-precision floating point

%c

A single character

%s

String

%q

String with any shell metacharacters escaped

%%

A percent sign by itself

Just after the leading percent sign, you can insert a numeric expression for the minimum width of the output. For example, “%5d” means to print a decimal number in a five-character-wide field, and “%6.2f” means a floating-point number in a six-character-wide field with two digits after the decimal point. Some useful numeric expressions are:

n

Minimum width n.

0n

Minimum width n, padded with leading zeroes.

n.m

Minimum width n, with m digits after the decimal point.

printf also interprets escape characters like “ ” (print a newline character) and “a” (ring the bell). See the echo command for the full list.

..................Content has been hidden....................

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