Linux Command: printf (bash)

Published on September 6, 2022 at 7:02 pm by LEW

Introduction

The printf command is a small program that creates formatted output. It is available in several programing languages, as well as several different command shells. In this post I will focus on using printf in the Bourne-again Shell (bash) used in many Linux distributions.

The printf command first appeared in early BSD releases. It became part of the first version of Portable Operating System Interface (POSIX).

Unlike the echo command, printf accepts a formatting string, and a more standardized interface. How echo works can vary somewhat depending on version and source (the echo command will usually have two variations; built in and external).

Syntax and Function

The basic syntax for printf is as follows

printf [format] [arguments]

The arguments are usually the text that is to be printed. The format string contains instructions on how to format the output.

Examples

If we want to add line feeds to the output, we use a format string. This format string will apply to all arguments. In this example we have two arguments; “Hello” and “World”. Each will receive a line feed. In the format block, the “%s” means to print arguments as strings, and the “\n” is the escape for a new line.

printf “%s\n” “Hello” “World”

Hello
World

It is also possible to embed text in the format string. To expand on the previous example, lets add the text “First” and “Second” to the formatting string.

printf “First %s\nSecond %s\n” “Hello” “World”

First Hello
Second World

Lets try something a bit more complex. if we want to print “Hello World” and “Foo Bar” on two separate lines. But we want “World” and “Bar” to line up in columns. We use a” %-10s” to print the first word with a column width of 10. For the second word we insert the new line character as we did above. In this case we have two formats and four arguments. So the formats will reapply to the second set of arguments, producing the output below.

printf “%-10s %s\n” “Hello” “World” “Foo” “Bar”

Hello     World
Foo       Bar

Options

Most of the options for printf occur in the format section. Between escape sequences and formatting commands there are quite a few items that can be added. The below list is limited to the most common ones that most people will encounter or want to use. For complete lists, check the man page for printf  and string literals  escape sequence references.

Conclusion

In this post we looked at the printf command, specifically in bash. We walked through a couple easy examples of formatting output that are just not possible with the echo command.

While printf may look a bit intimidating to new users, it just takes a little practice to master the basics of the command.

Add New Comment

Your email address will not be published. Required fields are marked *