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
Commandprintf
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:
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