How to use the printf command in a Shell script?

The printf command is used to format and output content, and its basic syntax is as follows:

printf format-string [arguments...]

The format-string is a string that specifies the output format, while arguments are the content to be outputted.

Here are some common printf format specifiers:

  1. %d: prints an integer.
  2. %f: output a floating-point number.
  3. %s: Print string.
  4. %c: display character.
  5. %x: outputs a hexadecimal number.

Here are some examples:

# 输出整数
printf "%d\n" 123     # 123

# 输出浮点数
printf "%f\n" 3.14    # 3.140000

# 输出字符串
printf "%s\n" "hello, world"   # hello, world

# 输出字符
printf "%c\n" 'A'     # A

# 输出十六进制数
printf "%x\n" 255     # ff

You can customize the output format as needed and use multiple parameters for output.

bannerAds