O'Reilly logo

Linux Pocket Guide, 2nd Edition by Daniel J. Barrett

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.\n" 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.\n" 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\n" "\""
This is a quote: "
$ printf "This is a quote: %q\n" "\""
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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required