Shell printf 命令
格式化占位符、宽度与对齐、数字格式,以及和 C 语言 printf 的对应关系。
Key Pointsprintf 不会自动加换行,格式串里要自己写 \n;参数多于占位符时会重复套用格式串。
基本格式
Bash
printf "hello %s\n" "world"
printf "%d + %d = %d\n" 2 3 5
printf "%.2f\n" 3.14159
printf "%x %X\n" 255 255Output
hello world
2 + 3 = 5
3.14
ff FF占位符
| Spec | Meaning |
|---|---|
%s | String |
%d | Integer |
%f | Float (default 6 decimals) |
%.2f | Float with 2 decimals |
%x / %X | Hex lower / upper |
%c | First character |
%% | Literal percent |
宽度与对齐
Bash
printf "%-10s|%10s|\n" "name" "score"
printf "%-10s|%10d|\n" "alice" 90
printf "%-10s|%10d|\n" "bob" 8Output
name | score|
alice | 90|
bob | 8|- left-aligns, the number is the minimum width, padded with spaces. Far more reliable than padding with echo.
参数多于占位符
Bash
printf "%s\n" one two three
printf "[%s] " a b c; echoOutput
one
two
three
[a] [b] [c] 数字格式
Bash
printf "%05d\n" 42
printf "%+d %+d\n" 5 -5
printf "%.1f%%\n" 99.55Output
00042
+5 -5
99.6%% is special in the format string; write %% for a literal percent. Forgetting it garbles generated nginx or cron files.基本格式
Bash
printf "hello %s\n" "world"
printf "%d + %d = %d\n" 2 3 5
printf "%.2f\n" 3.14159
printf "%x %X\n" 255 255Output
hello world
2 + 3 = 5
3.14
ff FF占位符
| 占位符 | 含义 |
|---|---|
%s | 字符串 |
%d | 整数 |
%f | 浮点,默认 6 位小数 |
%.2f | 保留 2 位小数 |
%x/%X | 十六进制小写 / 大写 |
%c | 首字符 |
%% | 百分号本身 |
宽度与对齐
Bash
printf "%-10s|%10s|\n" "name" "score"
printf "%-10s|%10d|\n" "alice" 90
printf "%-10s|%10d|\n" "bob" 8Output
name | score|
alice | 90|
bob | 8|- 表示左对齐,数字表示最小宽度,不够补空格。做表格对齐时比 echo + 手动空格可靠得多。
参数多于占位符
Bash
printf "%s\n" one two three
printf "[%s] " a b c; echoOutput
one
two
three
[a] [b] [c] 数字格式
Bash
printf "%05d\n" 42
printf "%+d %+d\n" 5 -5
printf "%.1f%%\n" 99.55Output
00042
+5 -5
99.6%printf 的格式串里 % 是特殊字符,要输出百分号必须写 %%。写 nginx 配置或 cron 时忘了这点,输出会错位。