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
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
Prints "Hello, World!" followed by a newline character.
Print formatted numbers
Prints the number 10 in decimal, hexadecimal, and octal formats.
Print with field width and precision
Prints "Alice" left-justified in a 10-character field and "30" zero-padded to 3 digits.
Print floating-point numbers
Prints the floating-point number 3.14159, rounded to two decimal places.
Using escape sequences
Demonstrates the use of tab (\t) and newline (\n) and carriage return (\r) escape sequences.