Typically, when writing bash scripts, we use echo to print to the standard output. [echo](https://linuxize.com/post/echo-command-in-linux-with-examples/) is a simple command but is limited in its capabilities.

To have more control over the formatting of the output, use the printf command.

The printf command formats and prints its arguments, similar to the C printf() function.

printf Command

printf is a shell builtin in Bash and in other popular shells like Zsh and Ksh. There is also a standalone /usr/bin/printf binary, but the shell built-in version takes precedence. We will cover the Bash builtin version of printf.

The syntax for the printf command is as follows:

printf [-v var] format [arguments]

Copy

The -v option tells printf not to print the output but to assign it to the variable.

The format is a string which may contain three different types of objects:

  • Normal characters that are simply printed to the output as-is.
  • Backslash-escaped characters which are interpreted and then printed.
  • Conversion specifications that describe the format and are replaced by the values of respective arguments that follow the format string.

The command accepts any number of arguments. If more arguments than format specifiers are provided, the format string is reused to consume all of the arguments. If fewer arguments than format specifiers are supplied, the extra numeric-format specifiers are set to zero value while string-format specifiers are set to null string.

#bash #printf #echo

Bash printf Command and Conversion specifications
2.95 GEEK