Whenever we work with bash, we use the echo command to print a standard output as it is easy to use and fits perfectly in our needs. But with the simplicity of echo, a few limitations are also attached like output formation with echo is not easy. So Printf is an effective alternative to echo. It can be easily used in bash just like we use it in other programming languages.
The syntax of printf command is:
printf [-v var] format [arguments]
Printf can have escape sequences, format specifiers, arguments, or ordinary characters. For example:
printf "hello world"
Bash Printf Command Examples
- The printf command accepts multiple numbers of arguments and if there are more arguments than format specifiers then the format string is reused for all the arguments. For example:
printf "%s\n" "Hello” “in” “bash”OutputHello in bash
- Another example of printf command is:
printf "Open points: %s\nClosed points: %s\n" “12" "21"OutputOpen points: 12 Closed points: 65
Open Points: %s\nClosed points: %s\nis a format while 12 and 21 are arguments. So there are two newline characters (\n) and two format specifiers (%s) that are replaced with the arguments while executing the command.
Printf Escape Characters
Some of the common escape characters for Printf are:
\n– Displays a new line.
\r– Displays a carriage return.
\v– Displays a vertical tab.
\\– Displays a backslash character.
\b– Displays a backspace character.
\t– Displays a horizontal tab.
In this tutorial, you have learned the Linux printf command with examples.