Home Study How to Use the Bash printf Command on Linux

How to Use the Bash printf Command on Linux

by Frank
Published: Last Updated on

Introduction

The Bash printf command gives you more flexibility and formatting choices than the echo command when writing to a Linux terminal window. Even printf’s peculiarities may be beneficial.

It’s one of the most fundamental aspects of working with software. You read what the application has written to the screen. Even with the Unix-derived and Linux-supported habit of command-line programs being as brief as possible, many applications only write to the terminal when something goes wrong. An crucial programming basic is informing the user of what is occurring, is going to happen, or has recently occurred.

The echo command in the Bash shell may write text to the terminal display. You may use it in scripts or on the command line, and it can handle variables and show their values if they are contained in the string. So, what is the point of printf? Isn’t text writing something that echo takes care of? Printf, on the other hand, provides more than just the ability to write strings to terminal windows. It gives you a lot of versatility when it comes to formatting the output, and it has a few additional tricks up its sleeve.

The printf command in Bash is similar to the printf function in C, however there are several changes. You’ll need to be aware of the changes if you’re familiar with C.

Creating Simple Strings

Let’s look at the differences between echo and printf when it comes to writing strings to the terminal.

echo here are some words
printf here are some words

Using echo and printf with unquoted words

While echo prints all of the words, printf simply publishes the first one. Also, printf does not print a new line. The output is smack dab in the middle of the command prompt. But first and foremost, all of the words must be cited in order for printf to act on them.

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

Using echo and printf with quoted words

That’s a step forward. We’ve printed all of the words, but we’re still waiting for a new line. That’s because printf only prints a new line if you specifically request one. This may sound inconvenient, but it allows you to choose whether or not to add one. You must add “n” in your string for printf to emit a new line. The “newline” escape sequence is used here.

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

Using echo and printf with quoted words and the newline character

You’ll use a newline sometimes and not others. In this example, one printf command utilizes a new line while the other does not.

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

Using two printfs to create a single line of text

Because the first printf does not print a new line, the output from the second printf is placed on the same line as “How-To.” To print a new line, the second printf uses n. The command prompt will now show on the line underneath the printed text.

Characters who have eluded capture

Here are some additional characters that may be used as escapes. You’ve previously seen how “n” works.

n: Switches to a new line.
r: This command prints a carriage return. The output cursor is returned to the beginning of the current line.
t: This command prints a tab character.
v: adds a vertical tab space to the page.
\: A backslash character is printed.
“: Displays a quotation mark.
b: Displays the backspace character.

The carriage return escape character is used to return the cursor to the beginning of the current line.

printf "Honey is the root of all evilrMoneyn"

Using the carriage return character to move back to the start of the line

The printf command reads from the left to the right. Until printf detects the “r” escape character, the string is written like regular text. The output cursor is repositioned at the beginning of the current line.

With the letter immediately below the “r” character, the string’s processing continues. The remainder causes printf to print “Money,” which replaces the phrase “Honey.”

The backslash “” character signals escape sequences, whereas the quotation mark “”” is used to quote strings. If you wish to print these characters, use a backslash to escape them. This instructs printf that they should be treated as literal characters.

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

Escaping characters so they are treated literally

Variables in Action

The use of variables with printf is quite similar to the use of variables with echo. To include a variable, such as this environment variable, use the dollar sign “$” as normal before it.

printf "Home directory: $HOMEn"

Using printf with an environment variable

String Formatting

Format strings are strings that specify the output format. You provide the format string text and additional values to work with as arguments.

Text, escape sequences, and format specifiers may all be included in the format string.

Printf’s format specifiers inform it what kind of argument it should accept, such as strings, numbers, or characters.

The most frequent format specifiers are shown below. A percent ” percent ” symbol precedes them all. You may print a percent sign by combining two percent signs ” percent percent “.

  • %s: Prints a string.
  • %c: Prints a single character.
  • %d: Prints an integer.
  • %f: prints a floating point number.
  • %u: Prints 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 floating point number in scientific notation, in lowercase.
  • %E: Prints a floating point number in scientific notation, in uppercase.
  • %%: Prints a percent “%” symbol.
printf "How-To %sn" "Geek"
printf "%s%s %sn" "How" "-To" "Geek"

Showing printf accepting "too many" arguments

The first command’s format string contains some content of its own. The string “Geek” is sent to printf as an argument. The “%s” format specifier matches it and prints it. Between the format string and the argument string, there is just a space. In C, a comma would be required to separate them, but with the Bash version of printf, a space suffices.

Only format specifiers and the newline escape sequence are included in the second format string. Each of the ” %s” format specifiers consumes the three string parameters in turn. Again, in C, a comma is required between each parameter, but the Bash printf function allows us to ignore this requirement.

Simply use the proper format specifier to output various sorts of arguments. Here’s a simple printf-based number conversion function. In decimal, octal, and hexadecimal notation, we’ll print the number 15.

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

using printf to print numerical values in different base notations

Let’s pare it down a little to make the example less cluttered.

printf "Hex: %xn" 15

Printing an hexadecimal value

The majority of us are used to seeing hexadecimal numbers rendered in uppercase and with values less than 0x10 preceded by a leading zero. We can do this by placing a width specifier between the percent sign ” % ” and the “X” character and utilizing the uppercase hexadecimal format specifier ” % X.”

This specifies the size of the field in which the argument should be printed to printf. Spaces have been added to the field. Two-digit numbers would be presented without any padding in this style.

printf "Hex: %2Xn" 15

printing an hexadecimal value in uppercase in a 2 character width field

We now have an uppercase value with a leading space written on it. By placing a zero in front of the two, we can have printf pad the field with zeroes instead of spaces:

printf "Hex: %02Xn" 15

printing an hexadecimal value in uppercase in a 2 character width field padded with zeroes

The precision specifier lets you specify how many decimal points should be included in the output.

printf "Floating point: %08.3fn" 9.243546

Using width and precision modifiers with a floating point number

This makes creating tables of results with perfectly aligned output a breeze. This command also displays another of Bash printf’s idiosyncrasies. If there are more arguments than format specifiers, the arguments are fed into the format string in batches until they are all used up. The amount of format specifiers in the format string determines the size of the batch that is processed at a given moment. Extra arguments sent to the printf function in C are ignored.

printf "Float: %8.3fn" 9.243546 23.665 8.0021

Using width and precision modifiers to create a neat table

Strings may also employ the width and precision specifiers. The strings are printed in a 10-character wide field using this command.

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

Using the width modifier with strings

By default, values are right-justified in their fields. To left-justify them, use a minus sign “-” immediately behind the percent “%” sign.

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

Using a left-justified width specifier with strings

The precision specifier allows you to choose the maximum number of characters that will be printed. The colon letters “:” are used to indicate the width field’s limitations. Not in the way the term “umbrellas” is shortened.

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

Using the precision modifier to limit the number of characters that are printed from a string

Even as an argument, the width specifier may be used. Instead of a numerical specifier, use an asterisk “*” and supply the width as an integer input.

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

Passing the width specifier as an argument to printf

Other oddities and gimmicks

The format specifiers in the format string will operate with values of the proper type, whether they’re supplied as ordinary arguments on the command line or created as the result of an expression.

This displays the result of adding two numbers:

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

Printing the sum of two numbers

The number of folders in the current working directory is printed by this command:

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

Counting directories with printf

The printf command prints a string that was returned from another program.

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

Printing the output from another command

If the string format specifier “percent s” is not given with an argument, printf returns null.

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

How printf deals with missing string arguments

If a numerical value is given by accident for the string format specifier ” % s,” it prints it as a string and does not complain. If you do this using the C printf, you’ll end up with a lot of problems. Your software is almost certainly going to crash. The Bash printf, on the other hand, doesn’t seem to mind.

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

How printf silently accepts integers as string values

If the integer format specifier “% d” is not given an argument, zero is printed.

printf "Integer: %dn"

How printf handles missing integer arguments

Bash will output an error message and printf will print zero if the integer format specifier ” % d” gets a string input by accident.

printf "Integer: %dn" "Seven"

How printf treats strings that are provided instead of integer arguments

Awkward symbols may be created by inputting their Unicode number, also known as a “code point.” The letter “u” is used to escape certain characters, followed by their Unicode value.

printf "The Euro symbol: u20ACn"

Printing an escaped Unicode value

To accommodate escape sequences in argument strings, use the ” % b” format specifier instead of the ” % s” string format specifier in the format string.

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

Using he %b format specifier to handle escape sequences in string arguments

The initial printf command does not recognize the newline escape sequence and does not process the Unicode value. The ” % b” format specifier is used in the second printf command. The Unicode character is handled appropriately, and a new line is displayed.

Horses for Courses

You may just need to echo some text into the terminal window on occasion. However, printf is the ideal tool for the task when you need to apply some positioning and formatting.

printf "%b" "Tha-" "tha-" "tha-" "that's all folks.n"

You may also like

Navhow is dedicated to teaching people all over the world how to do anything.

 

Subscribe

The Best How-To Newsletter Anywhere

©2022 Navhow, All Right Reserved