← 返回命令列表

Linux command

printf 命令

文本

复制后可按需替换文件名、目录或参数。

常用示例

Print formatted output

printf "%s\n" "Hello"

Print with variables

printf "Name: %s, Age: %d\n" "[name]" [25]

Print hexadecimal

printf "%x\n" [255]

Print with padding

printf "%10s\n" "text"

Print floating point

printf "%.2f\n" [3.14159]

说明

printf formats and prints data according to a format string, similar to the C library function of the same name. The format string can contain literal text, escape sequences like \n and \t, and conversion specifiers such as %s for strings, %d for integers, %f for floating-point numbers, and %x for hexadecimal. Unlike echo, printf provides precise control over output formatting and behaves consistently across shells and platforms. If more arguments are provided than the format string consumes, the format string is reused, making it easy to process lists. The command does not append a trailing newline unless explicitly included with \n in the format string. printf is part of GNU coreutils and is also available as a shell built-in in most shells. It is the preferred tool for generating formatted output in portable shell scripts.

参数

%s
String.
%d
Integer.
%f
Float.
%x
Hexadecimal.
%o
Octal.

FAQ

What is the printf command used for?

printf formats and prints data according to a format string, similar to the C library function of the same name. The format string can contain literal text, escape sequences like \n and \t, and conversion specifiers such as %s for strings, %d for integers, %f for floating-point numbers, and %x for hexadecimal. Unlike echo, printf provides precise control over output formatting and behaves consistently across shells and platforms. If more arguments are provided than the format string consumes, the format string is reused, making it easy to process lists. The command does not append a trailing newline unless explicitly included with \n in the format string. printf is part of GNU coreutils and is also available as a shell built-in in most shells. It is the preferred tool for generating formatted output in portable shell scripts.

How do I run a basic printf example?

Run `printf "%s\n" "Hello"` in a terminal, then adjust file names, paths, flags, or remote targets for your system.

What does %s do in printf?

String.