Shell printf Command
In the previous chapter we learned about the Shell echo command. In this chapter, we will learn about another Shell output command, printf.
printf(print formatted) is a Shell command for formatted output, derived from the C language'sprintf()function.
andechoUnlike,printfit does not automatically add newlines, and can precisely control the output format.
printf is defined by the POSIX standard, so scripts using printf are more portable than those using echo.
printf uses quoted text or space-separated arguments, and you canprintfuse format strings in it, and also specify string width, left/right alignment, etc. By default, printf does not,echoautomatically add newlines; we can add them manually.\n。
Why use printf?
- Format control: Can specify field width, precision, and alignment.
- Type safety: Different types of data (integers, floats, strings, etc.) have corresponding format specifiers.
- Portability: Behavior is more consistent across different systems and shells.
- Complex output: Suitable for generating structured output such as tables and reports.
Basic Syntax
The syntax of the printf command:
printf format-string [arguments...]
Parameter description:
- format-string: A string containing ordinary characters and format specifiers.
- arguments...: Variables or values corresponding to format specifiers.
Format specifiers start with a%character, followed by one or more characters, used to specify the output format. Common format specifiers include:
%s: String%d: Decimal integer%f: Floating-point number%c: Character%x: Hexadecimal number%o: Octal number%b: Binary number%e: Floating-point number in scientific notation
Workflow
- Parse the format string; output ordinary characters directly when encountered.
- When a format specifier (starting with
%at the beginning) is encountered:- Read the next argument.
- Process the argument according to the format specified by the specifier.
- Insert the result into the output.
- After processing all format specifiers, output the final result.
Practical Examples
1. Basic Usage
Example
printf "Hello, World!\n"
# Output with variables
name="Alice"
printf "Hello, %s\n" "$name"
Execution and output:
Example
Hello, World!
Hello, Alice
2. Common Format Specifiers
Example
printf "Decimal: %d\nHex: %x\nOctal: %o\n" 255 255 255
# Floating point
printf "Float: %f\nScientific: %e\n" 3.14159 3.14159
# String
printf "Name: %s\n" "Bob"
# Character
printf "First letter: %c\n" "A"
Execution result:
Decimal: 255 Hex: ff Octal: 377 Float: 3.141590 Scientific: 3.141590e+00 Name: Bob First letter: A
3. Formatting Control
Example
printf "|%10s|\n|%-10s|\n" "right" "left"
# Leading zeros in numbers
printf "Year: %04d\n" 23
# Floating-point precision
printf "Pi: %.2f\n" 3.14159
Execution result:
| right| |left | Year: 0023 Pi: 3.14
4. Multiple Argument Handling
Example
Execution result:
Apple 5 2.50 Orange 3 1.75
Extended Applications
1. Creating Table Output
Example
# Header
printf "%-15s %10s %10s %10s\n" "Item" "Quantity" "Price" "Total"
# Separator line
printf "%-15s %10s %10s %10s\n" "---------------" "----------" "----------" "----------"
# Data rows
printf "%-15s %10d %10.2f %10.2f\n" "Notebook" 3 2.50 7.50
printf "%-15s %10d %10.2f %10.2f\n" "Pen" 5 1.20 6.00
printf "%-15s %10d %10.2f %10.2f\n" "Eraser" 2 0.50 1.00
# Total row
printf "%-15s %10s %10s %10.2f\n" "" "" "Total:" 14.50
Output effect:
Item Quantity Price Total
--------------- ---------- ---------- ----------
Notebook 3 2.50 7.50
Pen 5 1.20 6.00
Eraser 2 0.50 1.00
Total: 14.50
2. Progress Bar Implementation
Example
for i in {1..20}; do
printf "\rProgress: [%-20s] %d%%" $(printf "%${i}s" | tr ' ' '#') $((i*5))
sleep 0.1
done
printf "\n"
Execution effect: Displays a gradually growing progress bar.
3. Color Output
Example
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color
printf "${RED}Error:${NC} Something went wrong\n"
printf "${GREEN}Success:${NC} Operation completed\n"
4. Formatted Output
Next, I will use a script to demonstrate the powerful features of printf:
Example
# author: Example
# url:www.example.com
printf "%-10s %-8s %-4s\n"Name Gender Weightkg
printf "%-10s %-8s %-4.2f\n"Guo Jing Male66.1234
printf "%-10s %-8s %-4.2f\n"Yang Guo Male48.6543
printf "%-10s %-8s %-4.2f\n"Guo Fu Female47.9876
Execute the script, and the output is as follows:
姓名 性别 体重kg 郭靖 男 66.12 杨过 男 48.65 郭芙 女 47.99
%s %c %d %fThese are all format specifiers.%sOutputs a string,%dinteger output,%coutputs a character,%foutputs a real number in decimal form.
%-10sRefers to a width of 10 characters (-Indicates left alignment; without it, right alignment is used. Any characters will be displayed within a width of 10 characters. If insufficient, spaces are automatically padded; if exceeded, the content is still displayed completely.
%-4.2fRefers to formatting as a decimal, where.2Refers to keeping 2 decimal places.
Example
# author: Example
# url:www.example.com
# format-string uses double quotes
printf "%d %s\n" 1 "abc"
# Single quotes have the same effect as double quotes
printf '%d %s\n' 1 "abc"
# Output can also be done without quotes
printf %s abcdef
# The format specifies only one argument, but the extra arguments are still output according to that format; format-string is reused
printf %s abc def
printf "%s\n" abc def
printf "%s %s %s\n" a b c d e f g h i j
# If there are no arguments, %s is replaced by NULL and %d by 0
printf "%s and %d \n"
Execute the script, and the output is as follows:
1 abc 1 abc abcdefabcdefabc def a b c d e f g h i j and 0
printf Escape Sequences
| Sequence | Description |
|---|---|
| \a | Alert character, usually the ASCII BEL character. |
| \b | Backspace |
| \c | Suppresses (does not display) any trailing newline character in the output result (only valid in argument strings controlled by the %b format specifier). Moreover, any characters remaining in the argument, any subsequent arguments, and any characters remaining in the format string are ignored. |
| \f | Form feed |
| \n | Newline |
| \r | Carriage return |
| \t | Horizontal tab |
| \v | Vertical tab |
| \\ | A literal backslash character |
| \ddd | A character representing a 1 to 3 digit octal value. Only valid in the format string. |
| \0ddd | A character representing a 1 to 3 digit octal value. |
Example
a string, no processing:<A\nB>
$ printf "a string, no processing:<%b>\n" "A\nB"
a string, no processing:<A
B>
$ printf "www.example.com \a"
www.example.com $ # No newline
Summary of Key Points
Key Knowledge Review
| Concept | Description | Example |
|---|---|---|
| Basic syntax | printf "format" args |
printf "%s" "hello" |
| Format specifier | Starts with %, specifies data type and format. | %d(integer),%f(floating point) |
| Escape character | Special character representation | \n(newline),\t(tab) |
| Field width | Controls the minimum width of output | %10s(10 characters wide) |
| Precision control | Number of decimal places for floating-point numbers | %.2f(2 decimal places) |
Common Format Specifiers Quick Reference Table
| Specifier | Purpose | Example input | Example output |
|---|---|---|---|
%s |
String | "text" |
text |
%d |
Decimal integer | 255 |
255 |
%x |
Hexadecimal integer | 255 |
ff |
%f |
Floating-point number | 3.14159 |
3.141590 |
%.2f |
2 decimal places | 3.14159 |
3.14 |
%c |
Single character | "A" |
A |
%% |
Percent sign | - | % |