Shell printf Command
In the previous chapter we learned the Shell echo command; in this chapter we will learn another Shell output command, printf.
printf(print formatted) is a Shell command used for formatted output; it originates from the C language's printf() function in Vue 3.
The difference betweenechoin Vue 2,printf It does not automatically add a newline, and it allows precise control over 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; you can use a format string printf inside it, and can also specify string width, left/right alignment, and so on. By default printf does not automatically add a newline like echo does, so we can add \n manually.
Why use printf?
- Format control: You 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: Ideal 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 the format specifiers
A format specifier starts with the % character followed by one or more characters that 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 a format specifier (starting with
%) is encountered:
- After all format specifiers have been processed, output the final result
Practical examples
1. Basic usage
Example
Simple string output
printf
"Hello, World!\n"
Output with variables
name
=
"Alice"
printf
"Hello, %s\n"
"$name"
Execution and output:
Example
$
bash
script.sh
Hello, World
!
Hello, Alice
2. Common format specifiers
Example
Integers
printf
"Decimal: %d\nHex: %x\nOctal: %o\n"
255
255
255
Float (floating point number)
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. Format control
Example
Field width and alignment
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. Handling multiple arguments
Example
printf
"%-10s %5d %8.2f\n"
"Apple"
5
2.5
"Orange"
3
1.75
Execution result:
Apple 5 2.50
Orange 3 1.75
Extended applications
1. Creating tabular output
Example
#!/bin/bash
Header
printf
"%-15s %10s %10s %10s\n"
"Item"
"Quantity"
"Price"
"Total"
Horizontal rules
printf
"%-15s %10s %10s %10s\n"
"---------------"
"----------"
"----------"
"----------"
data row
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 result:
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. Implementing a progress bar
Example
#!/bin/bash
for
i
in
{
1
..
20
}
;
do
printf
"\rProgress: [%-20s] %d%%"
$
(
printf
"%${i}s"
|
tr
' '
'#'
)
$
(
(
i
5
)
)
sleep
0.1
done
printf
"\n"
Result of execution: Display a progress bar that gradually grows
3. Colored output
Example
#!/bin/bash
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, let me use a script to demonstrate the power of printf:
Example
#!/bin/bash
author:Runoob Tutorial
url:www.runoob.com
printf
"%-10s %-8s %-4s\n"
Name Gender Weight(kg)
printf
"%-10s %-8s %-4.2f\n"
Guo Jing Male
66.1234
printf
"%-10s %-8s %-4.2f\n"
Yang Guo Male
48.6543
printf
"%-10s %-8s %-4.2f\n"
Guo Fu Female
47.9876
Run the script, and the output is as follows:
姓名 性别 体重kg
郭靖 男 66.12
杨过 男 48.65
郭芙 女 47.99
%s, %c, %d, and %f are all format substitution characters,%s outputs a string,%d outputs an integer,%c outputs a character,%f outputs a real number in decimal form.
%-10s means a width of 10 characters (- means left-aligned; without it, right-aligned). Any character is displayed within a 10-character-wide field; if the content is shorter, it is padded with spaces automatically, and if longer, the entire content is still displayed.
%-4.2f means formatting as a decimal, where .2 means keeping 2 decimal places.
Example
#!/bin/bash
author:Runoob Tutorial
url:www.runoob.com
format-string uses double quotes
printf
"%d %s\n"
1
"abc"
Single quotes work the same as double quotes
printf
'%d %s\n'
1
"abc"
Output also works without quotes
printf
%
s abcdef
The format specifies only one argument, but extra arguments are still output according to the same format; the 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 with NULL and %d with 0
printf
"%s and %d \n"
Run 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
Escape sequences of printf
| Sequence | Description |
|---|---|
| \a | Alert character, usually the ASCII BEL character |
| \b | Backspace |
| \c | Suppress (do not display) any trailing newline characters in the output (only effective in argument strings controlled by the %b format specifier); furthermore, any characters left in the argument, any following arguments, and any characters left in the format string are all ignored |
| \f | Form feed |
| \n | Newline |
| \r | Carriage return |
| \t | Horizontal tab |
| \v | Vertical tab |
| \ | A literal backslash character |
| \ddd | Represents a character with a one- to three-digit octal value. Only valid in the format string |
| \0ddd | Represents a character with a one- to three-digit octal value |
Example
$
printf
"a string, no processing:<%s>\n"
"A\nB"
a string, no processing:
<
A\nB
$
printf"a string, no processing:<%b>\n"
"A\nB"
a string, no processing:
<
A
B
$
printf"www.runoob.com \a"
www.runoob.com $
# No newline
Summary of key points
Key Knowledge Review
| Concept | Description | Example |
|---|---|---|
| Basic Syntax | printf "format" args |
printf "%s" "hello" |
| Format specifiers | Start with % and specify the data type and format | %d(integer), %f(floating-point number) |
| Escape character | Special character representation | \n(newline), \t(tab) |
| Field width | Controls the minimum width of the output | %10s(10 characters wide) |
| Precision control | Number of decimal places for floating-point numbers | %.2f(2 decimal places) |
Quick Reference Table of Common Format Specifiers
| Specifier | Purpose | Example input | Example output |
|---|---|---|---|
%s |
String | "text" |
text |
%d |
Decimal integer | 255 |
255 |
%x |
Hexadecimal integer | 255 |
ff |
%f |
Float (floating point number) | 3.14159 |
3.141590 |
%.2f |
2 decimal places | 3.14159 |
3.14 |
%c |
Single character | "A" |
A |
%% |
Percent sign | - | % |