Table of Contents#
- Syntax of
printf - Format Specifiers
- Escape Sequences
- Practical Examples
- Basic String Printing
- Formatting Numbers (Integers, Floats, Hex/Octal)
- String Alignment and Padding
- Date and Time Formatting
- Handling Special Characters
- Common Use Cases
- Best Practices
- References
Syntax of printf#
The printf command follows a straightforward syntax:
printf "format_string" [arguments...]format_string: A string containing plain text and format specifiers (placeholders for dynamic values).arguments: Values to be inserted into the format string, corresponding to the specifiers.
Key Notes:#
- Unlike
echo,printfdoes not automatically append a newline (\n) to the output. You must explicitly include\nin the format string. - If there are more arguments than specifiers,
printfreuses the format string cyclically until all arguments are processed.
Format Specifiers#
Format specifiers are the heart of printf. They define how arguments are interpreted and displayed. A specifier starts with % followed by optional modifiers and a type character.
Common Specifiers:#
| Specifier | Description | Example Use Case |
|---|---|---|
%s | String (text) | printf "Hello, %s\n" "Alice" |
%d/%i | Signed integer (decimal) | printf "Count: %d\n" 42 |
%f | Floating-point number | printf "Pi: %.2f\n" 3.14159 |
%c | Single character (ASCII value) | printf "Char: %c\n" 65 |
%x/%X | Hexadecimal (lowercase/uppercase) | printf "Hex: %x\n" 255 |
%o | Octal number | printf "Octal: %o\n" 64 |
%b | String with escape sequences interpreted | printf "%b" "Line1\nLine2\tTab" |
%% | Literal % character | printf "100%% complete\n" |
%n | Store number of characters written (advanced) | printf "Test%n" var; echo $var |
Modifiers for Specifiers:#
Modifiers adjust alignment, padding, and precision. For example:
%10s: Right-align string in a 10-character width (pads with spaces on the left).%-10s: Left-align string in a 10-character width (pads with spaces on the right).%.2f: Floating-point with 2 decimal places.%05d: Pad integer with leading zeros to 5 digits (e.g.,00042for 42).
Escape Sequences#
Escape sequences are special characters prefixed with \ to represent non-printable or reserved characters (e.g., newlines, tabs). printf interprets these sequences by default (unlike echo, which may require the -e flag in some shells).
Common Escape Sequences:#
| Sequence | Description | Example Output |
|---|---|---|
\n | Newline | Starts a new line |
\t | Horizontal tab | Adds a tab space |
\\ | Literal backslash | Prints \ |
\" | Literal double quote | Prints " |
\a | Alert (beep) | Emits a system beep |
\v | Vertical tab | Moves cursor down |
\r | Carriage return | Resets cursor to start |
Practical Examples#
Let’s dive into hands-on examples to understand printf’s versatility.
1. Basic String Printing#
Print a simple string with a dynamic name:
printf "Hello, %s! Welcome to Linux.\n" "Alice"Output:
Hello, Alice! Welcome to Linux.
2. Formatting Numbers#
Integers:#
Pad an integer to 5 digits with leading zeros:
printf "User ID: %05d\n" 123Output:
User ID: 00123
Floats:#
Display a float with 2 decimal places:
printf "Temperature: %.2f°C\n" 23.456Output:
Temperature: 23.46°C
Hex/Octal:#
Convert decimal 255 to hex and octal:
printf "Decimal: %d | Hex: %x | Octal: %o\n" 255 255 255Output:
Decimal: 255 | Hex: ff | Octal: 377
3. String Alignment and Padding#
Create a formatted table with left-aligned strings and right-aligned numbers:
# Header
printf "%-15s %-10s %5s\n" "Name" "Role" "Age"
# Rows
printf "%-15s %-10s %5d\n" "Alice" "Engineer" 30
printf "%-15s %-10s %5d\n" "Bob" "Designer" 28
printf "%-15s %-10s %5d\n" "Charlie" "Manager" 35Output:
Name Role Age
Alice Engineer 30
Bob Designer 28
Charlie Manager 35
4. Date and Time Formatting#
Combine printf with the date command to format timestamps:
printf "Current Time: %s\n" "$(date +'%Y-%m-%d %H:%M:%S')"Output (varies by time):
Current Time: 2024-05-20 14:30:45
5. Handling Special Characters#
Print quotes, backslashes, and newlines:
printf "He said, \"Hello\tWorld!\"\nThis is a new line.\n"Output:
He said, "Hello World!"
This is a new line.
6. Cyclic Argument Processing#
If there are more arguments than specifiers, printf reuses the format string:
printf "Item: %s | Price: $%d\n" "Apple" 1 "Banana" 0.5 "Orange" 0.75Output:
Item: Apple | Price: $1
Item: Banana | Price: $0
Item: Orange | Price: $0
(Note: %d truncates 0.5 and 0.75 to 0; use %f for floats.)
Common Use Cases#
- Scripting: Generate formatted logs or reports (e.g., CSV-like output).
- Data Processing: Align columns in command output (e.g.,
ls -lwith custom formatting). - User Prompts: Create user-friendly prompts in scripts (e.g.,
printf "Enter your name: "). - Text Generation: Automate creation of structured files (e.g., configs with placeholders).
Best Practices#
-
Always Use Double Quotes for Format Strings: Prevents shell word-splitting and preserves spaces/escape sequences.
# Good: printf "Name: %s\n" "John Doe" # Bad (may split "John Doe" into two arguments): printf Name: %s\n John Doe -
Explicitly Add Newlines: Unlike
echo,printfdoesn’t append\nautomatically. Omit it only if you want continuous output (e.g., progress bars). -
Match Specifiers to Arguments: Mismatched types (e.g., using
%dfor a string) cause undefined behavior. Use%sfor safety if unsure. -
Avoid Untrusted Format Strings: Never use user input as the format string (risk of format-string vulnerabilities). Always pass user input as an argument:
# Safe: user_input="Alice" printf "Hello, %s\n" "$user_input" # Unsafe (if user_input contains %x, %n, etc.): printf "$user_input\n" -
Test with Sample Data: Validate formatting with edge cases (e.g., empty strings, large numbers) to avoid unexpected output.
References#
printfman page:man printf- GNU Coreutils Documentation: printf
- Linuxize Tutorial: Linux printf Command Explained
By mastering printf, you’ll gain precise control over text formatting in the Linux command line. Its flexibility makes it a must-know tool for anyone working with shell scripts or command-line data processing. Experiment with the examples above to build familiarity, and refer to the best practices to avoid common pitfalls!