5158

26 分钟

#Bash 的 printf 命令

printf [OPTION] FORMAT [ARGUMENT]...

功能

数值和字符串之间的转换。

类型

可执行文件(/usr/bin/printf),属于 coreutils

参数

  • OPTION 选项:
    • --help - 显示帮助
    • --version - 显示版本
  • FORMAT - 格式字符串
  • ARGUMENT - 参数列表

#格式

符号说明
\"双引号
\\反斜杠
\a警告声(BEL)
\b退格
\c不再产生任何输出
\eEscape 字符
\f换页符(form feed)
\n换行符
\r回车符
\t水平制表符
\v垂直制表符
\NNN八进制值为 NNN 的字节(1 到 3 位)
\xHH十六进制值为 HH 的字节(1 到 2 位)
\uHHHHUnicode 字符(ISO/IEC 10646),十六进制值 HHHH(4 位)
\UHHHHHHHHUnicode 字符,十六进制值 HHHHHHHH(8 位)
%%百分号(%)本身
%b将参数作为带有反斜杠转义的字符串输出;八进制转义格式为 \0 或 \0NNN
%q输出可作为 shell 输入的格式,并使用 POSIX 提议的 $'' 语法对不可打印字符进行转义
%c单个字符
%s字符串
%d有符号十进制整数
%i有符号十进制整数,同 %d
%u无符号十进制整数
%o无符号八进制整数
%x无符号十六进制整数,字母小写
%X无符号十六进制整数,字母大写
%f浮点数,字母小写
%F浮点数,同 %f
%e浮点数,科学计数法,字母小写
%E浮点数,科学计数法,字母大写
%g浮点数,省略小数末尾的 0,值较大时使用科学计数法,字母小写
%G浮点数,省略小数末尾的 0,值较大时使用科学计数法,字母大写

#示例

$ printf "Hello World\n" Hello World $ printf "Name: %s, Age: %d\n" "Alice" 18 Name: Alice, Age: 18

#推荐阅读

#手册

PRINTF(1) User Commands PRINTF(1) NAME printf - format and print data SYNOPSIS printf FORMAT [ARGUMENT]... printf OPTION DESCRIPTION Print ARGUMENT(s) according to FORMAT, or execute according to OPTION: --help display this help and exit --version output version information and exit FORMAT controls the output as in C printf. Interpreted sequences are: \" double quote \\ backslash \a alert (BEL) \b backspace \c produce no further output \e escape \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \NNN byte with octal value NNN (1 to 3 digits) \xHH byte with hexadecimal value HH (1 to 2 digits) \uHHHH Unicode (ISO/IEC 10646) character with hex value HHHH (4 digits) \UHHHHHHHH Unicode character with hex value HHHHHHHH (8 digits) %% a single % %b ARGUMENT as a string with '\' escapes interpreted, except that octal escapes are of the form \0 or \0NNN %q ARGUMENT is printed in a format that can be reused as shell in‐ put, escaping non-printable characters with the proposed POSIX $'' syntax. and all C format specifications ending with one of diouxXfeEgGcs, with ARGUMENTs converted to proper type first. Variable widths are handled. NOTE: your shell may have its own version of printf, which usually su‐ persedes the version described here. Please refer to your shell's doc‐ umentation for details about the options it supports. AUTHOR Written by David MacKenzie. REPORTING BUGS GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT Copyright © 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO printf(3) Full documentation <https://www.gnu.org/software/coreutils/printf> or available locally via: info '(coreutils) printf invocation' GNU coreutils 9.4 April 2024 PRINTF(1)

创建于 2025/11/20

更新于 2025/11/20