printf Command

The printf command formats and prints data to standard output. It's similar to the C language printf function and offers more control over output formatting than echo.

Syntax

printf FORMAT [ARGUMENT]...

Description

The printf command allows for precise control over the output format using format specifiers and escape sequences. This makes it particularly useful in shell scripting for generating structured output.

Common uses include:

  • Formatting text output for display or logging.
  • Creating formatted reports.
  • Generating data in specific formats for other programs.
  • Working with numerical data in different bases (decimal, hexadecimal, octal).

Format Specifiers

Specifier Description
%s String
%d, %i Signed decimal integer
%u Unsigned decimal integer
%o Unsigned octal integer
%x, %X Unsigned hexadecimal integer (lowercase/uppercase)
%f Floating-point number
%c Character
%% Literal % character

Escape Sequences

Sequence Description
\ Backslash
\a Alert (bell)
\b Backspace
\c Produce no further output
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab

Examples

Print a simple string with newline

printf "Hello, World!\n"

Prints "Hello, World!" followed by a newline character.

Print formatted numbers

printf "Decimal: %d, Hex: %x, Octal: %o\n" 10 10 10

Prints the number 10 in decimal, hexadecimal, and octal formats.

Print with field width and precision

printf "Name: %-10s Age: %03d\n" "Alice" 30

Prints "Alice" left-justified in a 10-character field and "30" zero-padded to 3 digits.

Print floating-point numbers

printf "Value: %.2f\n" 3.14159

Prints the floating-point number 3.14159, rounded to two decimal places.

Using escape sequences

printf "Column1\tColumn2\nLine1\nLine2\rLine3"

Demonstrates the use of tab (\t) and newline (\n) and carriage return (\r) escape sequences.

See also