printf Command Examples in Linux

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?"

will print:

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.

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
Related Post