Oct 23, 2023 6 min read

Bash printf Command

Use printf command in Bash with our step-by-step tutorial. A printf command prints the formatted text and variables with options.

Bash printf Command
Table of Contents

Introduction

Before we talk about Bash printf command, let's understand-What is printf Command ?

The printf command in Bash is used for formatted printing. It allows users to print formatted text and variables by specifying various format options. printf is a versatile tool for displaying output in a specific format, controlling the placement of variables, and formatting numerical values, strings, and more.

In this tutorial, you will understand how printf command works. We will also address a few FAQs on Bash printf command.

printf Command

printf is a shell that comes standard with Bash and other popular shells such as Zsh and Ksh. Although there is a separate /usr/bin/printf binary, the built-in version of the shell takes precedence. The built-in version of printf in Bash will be covered.

The printf command has the following syntax:

printf [-v var] format [arguments]

The -v option instructs printf to assign the output to a variable rather than printing it.

The format is a string that can contain one of three object types:

  • Characters that are just printed as-is to the output.
  • Backslash-escaped characters that are interpreted and printed.
  • The values of the relevant arguments that follow the format string replace the conversion specifications that explain the format.

Any number of parameters can be passed to the command. If there are more arguments than format specifiers, the format string is used to consume them all. If there are fewer arguments than format specifiers, the additional numeric-format specifiers are set to zero, while string-format specifiers are set to null.

When using the printf command, there are a few things to keep in mind:

  • Before providing the inputs to the printf command, the shell will substitute any variables, wildcard matches, and special characters.
  • The literal value of each character included within the quotations will be kept when using single quotes. There will be no expansion of variables or commands.
printf "Open issues: %s\nClosed issues: %s\n" "34" "65"
Output

Open issues: 24
Closed issues: 35

The string issues Open: %s\nClosed issues: %s\n is the format while "34" and "65" are arguments. Two newline characters (\n) and two format specifiers (%s) are replaced with the arguments.

At the end of each line, the printf command does not append a newline character (\n).

Backslash-escaped Characters

When used in the format string or an argument corresponding to a %b conversion specifier, backslash-escaped characters are processed. The following is a list of the most frequently used escape characters:

  • \\ - Shows the backslash character.
  • \b - Shows the backspace character.
  • \n - Adds a new line to the document.
  • \r - Represents a carriage return.
  • \t - Displays a horizontal tab.
  • \v - Displays a vertical tab.

Conversion Specifications

The following is an example of a conversion specification:

%[flags][width][.precision]specifier

Each conversion specification begins with a percent sign(%), includes optional modifiers and concludes with one of the letters aAbcdeEfgGioqsuxX, which represents the data type (specifier) of the associated parameter.

Type conversion specifier

The type conversion specifier is a character that determines how the corresponding argument should be interpreted. This character is mandatory and appears after the optional fields.

The following is a list of all type conversions and their functions:

  • %b - Print the argument while expanding backslash escape sequences.
  • %q - Displays the shell-quoted argument, which can be used as input again.
  • %d,%i - Generate a signed decimal integer from the parameter.
  • %u - Display the argument as an unsigned decimal integer.
  • %o - Display the argument as an unsigned octal integer.
  • %x, %X - Print the argument as an unsigned hexadecimal integer with. Lower-case characters are printed by %x, while upper-case letters are printed by %X.
  • %e, %E - Print the argument in exponential notation as a floating-point value. Lower-case letters are printed by  %e, while upper-case letters are printed by %E.
  • % a, %A - Print the argument in hexadecimal fractional notation as a floating-point value. Lower-case letters are printed by %a, whereas upper-case letters are printed by %A.
  • %g, %G - Print the argument as a floating-point number in either normal or exponential notation, depending on the precision and value. Lower-case letters are printed with %g, whereas upper-case letters are printed with %G.
  • %c - Print the argument as a single character.
  • %f - Returns a floating-point number for the argument.
  • %s - As a string, print the argument.
  • %% - A literal percent symbol must be used.

Negative, zero, and positive numbers are represented by an unsigned number, whereas negative, zero, and positive numbers are represented by a signed number.

The following program prints the number 100 in three distinct number systems:

printf "Decimal: %d\nHex: %x\nOctal: %o\n" 100 100 100
Output

Decimal: 100
Hex: 64
Octal: 144

Flags directive

The first optional modifiers are flags, which are used to set the justification, leading zeros, prefixes, and other options.

Here are a few of the most common:

  • - - Within the field, alugn the written text to the left. The text is right-aligned by default.
  • + - Use a + or - sign to prefix the numbers. Only negative numbers are prefixed with a negative sign by default.
  • 0 - Uses leading zeros instead of space to pad numbers.
  • blank - positive numbers should be preceded by a blank space, while negative numbers should be preceded by a minus (-).
  • # - An alternative number format.

Width directive

The width directive, which is filed after any flag characters, defines the minimum amount of characters that should be converted.

The width of the text output is padded with spaces if it is less than the specified width. A non-negative decimal integer or an asterisk (*) can be used to specify the width.

Here's an example:

printf "%20s %d\n" Mark 305

Set the field length to at least 20 characters in %20s. Because the output is right-justified by default, blanks are appended before the text. Use the - flag to align the text to the left (%20s).

Output

Jane 305

When an asterisk (*) is used as a width directive, the conversion field's width is determined by a width argument that comes before the formatted argument.

The width is set to 10 in the example below:

printf "%0*d" 10 5

0 is a flag that causes the integer to be padded with leading zeros rather than blanks. There will be at least 10 characters in the result text:

Output

0000000005

Precision directive

The .precision modifier consists of a dot (.) followed by a positive integer or an asterisk (*) that specifies the number of string or digit characters or decimal places to be written, depending on the specifier type.

The effect of the precision is as follows:

  • The precision sets the minimum number of digits to be printed if the conversion type is an integer. Leading zeros are written if the number of digits in the argument is less than precision.
  • The precision determines the number of digits that follow the decimal-point character if the conversion type is floating-point. The accuracy is set to 6 by default.
  • The precision determines the maximum number of characters to be printed if the conversion type is a string. The surplus characters are trimmed if the number of characters in the argument exceeds precision.

An example of how to round a floating-point number to three decimals is as follows:

printf "%.3f" 1.61803398
Output

1.618

When precision is set to an asterisk (*), the precision argument preceding the formatted argument determines its value.

printf "%.*f" 3 1.61803398
Output

1.618

FAQs on Bash Printf Command

How does printf work in Bash?

printf consists of a format string followed by arguments that match the format specifier placeholders in the format string. It replaces these placeholders with the formatted values of the provided arguments.

What are format specifiers in printf?

Format specifiers in printf are placeholders that define how variables are formatted and displayed. They start with % and are followed by characters that represent the type and format of the variable.

What are some commonly used format specifiers in printf?

Common format specifiers in printf include %s for strings, %d for decimal (integer) values, %f for floating-point numbers, %c for a single character, %x for hexadecimal numbers, and more.

Can printf format and display variables in Bash?

Yes, printf can format and display variables by using format specifiers in the format string and providing variables as arguments that correspond to the placeholders.

How can I align and pad values using printf?

By specifying width and alignment options in the format specifiers, printf can align and pad values. For example, %10s will left-align and pad a string with spaces to a width of 10 characters.

Can I format and display numerical values with custom precision using printf?

Yes, printf allows for custom precision control when formatting numerical values. For example, %0.2f will format a floating-point number with a precision of 2 decimal places and pad with zeros if required.

What is the difference between printf and echo?

Unlike echo, printf provides more control over formatting and output. It allows for precise formatting, handling of escape sequences, and greater flexibility in displaying variables and special characters.

Conclusion

The printf command outputs formatted text after receiving a format and arguments.

If you have any queries, please leave a comment below and we’ll be happy to respond to them.

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to DevOps Tutorials - VegaStack.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.