How to Use the Bash Printf Command on Linux

The Bash printf command gives you better Terminal control and more formatting options than the echo command. So, in this article, I will show you how to use the Bash printf command on Linux.

How to Use the Bash Printf Command on Linux

Printf on Terminal

This is one of the most basic parts of interacting with a program. The program writes something to the screen and you read it. Even considering the convention of command-line programs derived from Unix and Linux, the more concise the better — many programs only log errors to the Terminal if something goes wrong. Telling the user what is happening, or is about to happen, or has just happened is an essential programming principle.

The bash shell has an echo command that can write text to the Terminal. It can process variables and display their values ​​if they are printed as strings and you can use it in scripts or on the command line. So why does printf exist? Does the Echo have problems writing texts? Well, printf provides functions other than the simple act of writing a text string to Terminal. It allows you to format the output with great flexibility and it also has other uses.

The Bash printf command is modeled on the printf function from the C language, but it’s still a little different. If you know C, you’ll need to notice those differences.

Writing basic strings

Let’s see how echo and printf are different when they print the strings to the terminal.

echo here are some words
printf here are some words

How to Use the Bash Printf Command on Linux 91

The echo command prints all words but printf only prints the first word. Also, no newlines are printed. The output is placed right on the command prompt. First thing though, for printf to work with all words, you need to enclose the string in double quotes.

echo here are some words
printf "here are some words"

How to Use the Bash Printf Command on Linux 92

Printf printed all the words but we still don’t get newlines. That’s because with printf you only get a newline if you ask for it. That might sound like a con, but it lets you decide whether to add a newline or not. To make printf print a newline, you need to add “n” to your string.

echo here are some words
printf "here are some wordsn"

How to Use the Bash Printf Command on Linux 93

Sometimes you will use a newline and sometimes not. This is the case where one printf statement uses a newline and the other does not.

printf "How-To " && printf "Geekn"

How to Use the Bash Printf Command on Linux 94

Because the first printf command does not print a newline, the output from the second printf is placed immediately after “How-To” and on the same line. The second printf uses n to print a newline. This causes the command prompt to appear on the line below the printed text.

Other special characters

Here are some other special characters you can use like “n”.

  • n: Create a new line.
  • r: Prints text to the beginning of the line and returns the cursor to the current position.
  • t: Print a tab character.
  • v: print vertical tab space.
  • \: Prints a backslash character.
  • “: Prints a double quote character.
  • b: Print spaces.

A newline escape character and returns the cursor to the current position.

printf "Honey is the root of all evilrMoneyn"

How to Use the Bash Printf Command on Linux 95

The printf command processes its input from left to right. The string is printed as normal text until printf encounters the “r” character. The output cursor is moved back to the beginning of the current line.

When the printf command encounters the “r” character, it will print the text after the “r” character, ie Money overwrites Honey and returns the cursor to the current position. That is, the pointer will now be at the end of the word evil.

Double quotes “”” are used to quote strings, and the backslash character “” denotes plain text. If you want to print these characters, you need to remove them with a backslash. This causes printf to treat them as normal literal characters.

printf "This is a tTab, this is a quotation mark ", and this \ is a Backslashn"

How to Use the Bash Printf Command on Linux 96

Using variables

Using variables with printf is very similar to echo. To include a variable, like this environment variable, precede it with the dollar sign “$” as usual.

printf "Home directory: $HOMEn"

How to Use the Bash Printf Command on Linux 97

String Format

String format is to define the output format of the string. You provide text and other values ​​as arguments to format the string.

Format strings can include text, special character strings, and format codes. Format values ​​tell printf the type of argument, such as string, integer, or character.

These are the most common formats. All of them are preceded by a percent sign “%”. To print the percentage sign, you use the two percent signs together “%%”.

  • %s: Print a string.
  • %c: Print a character.
  • %d: Print an integer.
  • %f: prints a real number.
  • %u: Print an unsigned integer.
  • %o: Prints a value in octal.
  • %x: Prints a value in hexadecimal, in lowercase.
  • %X: Prints a value in hexadecimal, in uppercase.
  • %e: Prints a real number in scientific notation, in lowercase.
  • %E: Prints a real number in scientific notation, in uppercase.
  • %%: Prints the “%” percentage symbol.
printf "How-To %sn" "Geek"
printf "%s%s %sn" "How" "-To" "Geek"

How to Use the Bash Printf Command on Linux 98

The string format in the first command includes some text of its own. I pass the string “Geeks” as an argument to printf. It is printed in the format “%s”. Note that there is only one space between the format string and the argument. In C you need commas to separate them but with the Bash version of printf, using spaces is enough.

The second format string contains only the format codes and the new text string. The three string arguments are used by each word of the format “%s” in turn. Again, in C you need to put a comma between each argument but Bash printf lets us forget that.

To print different types of arguments, simply use the appropriate formatting tool. This is a fast numeric conversion built in printf. I will print the value 15 as decimal, octal, and hexadecimal notation.

printf "Dec: %dnOct: %onHex: %xn" 15 15 15

How to Use the Bash Printf Command on Linux 99

Another less messy example.

printf "Hex: %xn" 15

How to Use the Bash Printf Command on Linux 100

Most of us are used to seeing hexadecimal values ​​in uppercase and with values ​​less than 0x10 printed with leading zeros. We can do this by using the uppercase hexadecimal format code “%X” and placing a width specifier between the percent sign “%” and the character “X”.

This tells printf the width of the field in which the argument will be printed. This field is padded with spaces. With this format, two-digit values ​​will be printed without any padding.

printf "Hex: %2Xn" 15

How to Use the Bash Printf Command on Linux 101

We now get an uppercase value, printed with leading spaces. We can make printf print zeroes instead of spaces by putting a zero in front of 2:

printf "Hex: %02Xn" 15

How to Use the Bash Printf Command on Linux 102

The precision specifier allows you to set the number of decimal points to print.

printf "Floating point: %08.3fn" 9.243546

How to Use the Bash Printf Command on Linux 103

This makes it easy to create resulting tables with neatly aligned output. This next command also demonstrates one of the other quirks of Bash printf. If there are more arguments than the format number, the arguments will be included in the format string in order until all arguments are used up.

printf "Float: %8.3fn" 9.243546 23.665 8.0021

How to Use the Bash Printf Command on Linux 104

You can also use characters that specify width and precision with strings. This command prints strings in a field 10 characters wide.

printf "%10s %dn" "coats" 7 "shoes" 22 "Umbrellas" 3

How to Use the Bash Printf Command on Linux 105

By default, values ​​are right aligned in their fields. To left-align them, use the minus sign “-” right after the percent sign “%”.

printf "%-10s %d" "coats" 7 "shoes" 22 "Umbrellas" 3

How to Use the Bash Printf Command on Linux 106

The precision specifier can be used to set the maximum number of characters to be printed. We are using colon characters “:” to display the limit of the width field.

printf ":%10.6s:n" "coats" "shoes" "Umbrellas"
printf ":%-10.6s:n" "coats" "shoes" "Umbrellas"

How to Use the Bash Printf Command on Linux 107

The width parameter can even be passed as an argument. Use an asterisk “*” instead of a numeric symbol and pass the width as an integer argument.

printf "%*sn" 20 "Rightmost" 12 "Middle" 5 "leftmost"

How to Use Bash Printf Command on Linux 108

Other tricks

Format specifiers inside the format string will work with the appropriate values, whether they are supplied on the command line as regular arguments or they are generated as the output of an expression.

This command prints the sum of two numbers:

printf "23+32=%dn" $((23+32))

How to Use the Bash Printf Command on Linux 109

This command prints out the number of directories in the current working directory:

printf "There are %d directoriesn" $(ls -d */ | wc -l)

How to Use the Bash Printf Command on Linux 110

This printf command prints a string returned from another command.

printf "Current user: %sn" $(whoami)

How to Use the Bash Printf Command on Linux 111

If the string format code “%s” is not supplied with an argument, printf will not print.

printf "One: %s two: %sn" "Alpha"

How to Use the Bash Printf Command on Linux 112

If the string format code “%s” is given a numeric value, it will still print the number.

printf "One: %s two: %sn" "Alpha" 777

How to Use the Bash Printf Command on Linux 113

If the integer format code “%d” receives no arguments, it prints 0.

printf "Integer: %dn"

How to Use the Bash Printf Command on Linux 114

If an integer format “%d” receives a string argument, Bash will print an error message and printf will print 0.

printf "Integer: %dn" "Seven"

How to Use the Bash Printf Command on Linux 115

Confusing symbols can be created using Unicode or their “code point”. They are created with the letter “u” followed by their Unicode value.

printf "The Euro symbol: u20ACn"

How to Use the Bash Printf Command on Linux 116

To include the escape sequence in the argument string, you must use the “%b” format specifier in the format string, not the “%s” string formatter.

printf "%s" "u20ACn"
printf "%b" "u20ACn"

How to Use the Bash Printf Command on Linux 117

The first printf statement does not handle Unicode values ​​and it does not recognize the newline character. The second printf statement uses the format code “%b”. This correctly handles the Unicode character and a printed newline.

Leave a Reply