The printf command is similar to echo, but provides the user with much more control over how the output is formatted. You can supply various format characters within the text you want to output, using a backslash (\) to indicate when they are being used. For example:
# printf "Hello.\nWhat's your name?"
Hello. What's your name?
This is because \n is the newline format character, and automatically adds a new line wherever it is placed.
The printf command also supports conversion characters, which use a percent sign (%) to indicate when they are being used. Conversion characters are typically used in
scripts to change the output of a variable, like dictating the number of decimal places to print after a precise calculation.
If you encounter below error while running the printf command:
printf: command not found
you may try installing below package as per your choice of distribution:
|OS X||brew install coreutils|
|Debian||apt-get install coreutils|
|Ubuntu||apt-get install coreutils|
|Alpine||apk add coreutils|
|Arch Linux||pacman -S coreutils|
|Kali Linux||apt-get install coreutils|
|CentOS||yum install coreutils|
|Fedora||dnf install coreutils|
|Raspbian||apt-get install coreutils|
printf Command Examples
1. Print a text message:
# printf "%s\n" "Hello world"
2. Print an integer in bold blue:
# printf "\e[1;34m%.3d\e[0m\n" 42
3. Print a float number with the Unicode Euro sign:
# printf "\u20AC %.2f\n" 123.4
4. Print a text message composed with environment variables:
# printf "var1: %s\tvar2: %s\n" "$VAR1" "$VAR2"
5. Store a formatted message in a variable (does not work on zsh):
# printf -v myvar "This is %s = %d\n" "a year" 2016