Chapter 11: Formatting output with printf

printf is a bash built-in and does not add a newline by default.

1 printf "The results are %d and %d\n" $((2+2)) $((3/1))

We can enclose variables within the printf statement:

1 myvar=Linux
2 printf "$myvar is fun to work with.\n"

When you enclose your arguments with single quotes the variable and command will be treated as plain text. You have to enclose the arguments with double quotes if you want the variable and command to be expanded.

We can assign printf output to a variable in 2 ways:

1 # Method 1
2 release=$(printf "$(uname -r)")
3 printf release
4 
5 # Method 2
6 printf -v release "$(uname -r)"
7 printf release

The -v option causes the output to be assigned to the variable var rather than being printed to the standard output.

Width Modifiers

1 printf "%20s" Ronaldo
2 #             Ronaldo

Since Ronaldo is 7 characters, and the specified width is 20, it will add spaces to justify the width.

We can use a - to justify the alignment:

1 printf "%-10s" Ronaldo
2 #Ronaldo

For integers, we can replace the space with zeros by adding a 0 flag modifier:

1 printf "%010d" 7
2 #0000000007

Pricision Modifiers

It is used to decide the number of characters to be printed, use the . followed by number of characters:

1 printf "%.7s \n" "Ronaldo has joined Manchester United"
2 #Ronaldo

We can also use * to specify the precision:

1 printf "%.*s \n" 7 "Ronaldo has joined Manchester United"
2 #Ronaldo