How to Print a Variable With Bash printf [10 Examples Inside]

Try this guide with our instant dedicated server for as low as 40 Euros

bash printf

The success of a Bash script is in part dependent on how well it presents data to the standard output or a file. 

Out of the two popular Bash output statements, printf is a much-recommended option that developers prefer over the traditional echo statement. While echo is a great choice for quick output, printf is the go-to choice to format the output. 

So, whether you’re a beginner or an experienced Linux user, understanding the basics of printf can significantly improve your scripting skills.

In this article, we’ll provide a comprehensive overview of the bash printf command. We’ll start with a look at the basic statement syntax and then discuss 10 use cases where you can apply the printf statement for formatting and printing data.

Let’s start with the syntax and usage of this command. 

Table Of Content

  1. The Syntax of Bash printf
  2. The printf Specifiers
  3. Bash printf Examples
  4. Conclusion
  5. FAQs

The Syntax of Bash printf

The printf statement is pretty straightforward. You give it a format string, which is like a template for how you want the output to look, and then provide the actual values (arguments) that will fill in the blanks in that template.

Here’s a breakdown of the syntax:

# printf [-v var] [format specifiers] [arguments]

  • [-v var]: The optional -v flag allows you to assign the output to the variable [var] instead of displaying it in the standard output.
  • [format specifiers]: These strings establish the formatting rules for the variable used in the output. 
  • [arguments]: Arguments can take the form of any value or variable, and they are referenced by the [format specifiers]

Note: If the count of arguments exceeds the number of format specifiers, the format string is cyclically reused until the last argument is interpreted.

In cases with fewer format specifiers than arguments, numeric formats default to zero (0), while string formats default to null (empty).

The printf Specifiers

The following table provides a comprehensive list of standard printf format specifiers along with their descriptions:

printf specifiers

You can extend format specifiers with format modifiers, altering their behavior. Insert these modifiers between the % character and the format character. You can opt for several formats, including the following:

  • <N>: Indicates a minimum field width; if the output is shorter, it is padded with spaces, and for longer output, the field expands to contain the entire input.
  • . (dot): When combined with a field width, it truncates longer text instead of expanding the field.
  • -: Aligns printed text to the left. Note that the default alignment is to the right.
  • 0: Pads with zeros instead of spaces.
  • <space>: Inserts a space between a positive number and a minus sign (-) for negative numbers.
  • +: Displays a sign (+ for positive, – for negative) for all numerical values.
  • ‘: Applies the current thousands grouping separator to the integer part of decimal output based on the current LC_NUMERIC setting.

Bash printf Examples

Now that you know the various options you can use with the printf option, let’s see the statement in action. We’ll see ten use cases where you can use the statement to format the output. However, let’s first see the prerequisites:

Prerequisites

  • A system running a mainstream Linux distribution
  • An account with admin privileges

Unlike echo, which is ideal for single statements in the Bash shell, printf is more suited for formatting the output of the scripts. It is a great option for promoting code reusability and automation through scripts. 

The examples below show different ways to format output with the printf command. 

Use Case #1: Separate Output with a Newline Character

Like echo, printf outputs unformatted text on a single line when you use it without format specifiers. 

You can introduce line breaks and distinguish entries by incorporating the \n (newline) format specifier:

Separate Output with a Newline Character

Use Case #2: Print Multiple Variables

Here’s the process you can follow to print several variables in Bash using printf:

  • Launch your preferred text editor to edit a script file. We’ll use the traditional Vi editor with the following command:

# vi script.sh

  • Add the following lines to the script files:

#!/bin/bash
printf "Enter your name:\n"
read name
printf "Enter your surname:\n"
read surname
printf 'Welcome, %s %s!\n' "$name" "$surname"

In this script, %s in the format string points to the variables defined in the previous lines, and \n instructs printf to add a newline character.

  • Save the file and exit the text editor. Since we’re using Vi, we’ll use:

:wq

  • Run the script:

bash script.sh

  • Enter the requested values for the two variables and verify the outcome:

script for the two variables

 

 

 

 

The printf command in the script merges the provided values for “name” and “surname” and outputs a welcoming message.

Use Case #3: Print Variable in a Mock Table

You can automatically add dynamic padding or change the variable output alignment with printf. For this, follow these steps.

  • Create a script file using Nano:

# nano table.sh

  • Add the following lines and save the script:

#!/bin/bash
var='hello'
printf '|%8s|\n' "$var"

In this script, %10s ensures that the pipe symbols have ten characters by padding the variable output with whitespace characters. The s function handles the supplied variable as if it were a string.

  • Run the following command and check the output:

# bash table.sh

Print Variable in a Mock Table

By default, this command prints the variable wrapped in pipe symbols and aligns it to the right.

  • Next, edit the script to add the modifier after the % character in the format string to align the output to the left:

#!/bin/bash
var='hello'
printf '|%-8s|\n' "$var"

 

  • Run the modified script and check the result:

# bash table.sh

 

output align to left

This change in the script adjusts the text alignment in the printf output, aligning the variable to the left within the pipe symbols.

Use Case #4: Add Decimal Points

To use printf with the %f format specifier to treat the input as a floating-point number and add precision to two decimal places, follow these steps:

  • Create a bash script with Vi:

# vi precisionscript.sh

  • Enter the following lines and save the script:

#!/bin/bash
printf "Enter a decimal number:\n"
read number
printf "%6.2f\n" "$number"

In this script, %6.2f specifies the format to treat the input variable as a floating-point number and rounds it to two decimal places. The 6 represents the total width of the field, and the 2 represents the precision.

  • Run the script and check the output:

# bash precisionscript.sh

Add Decimal Points

The script prompts you to enter a decimal number, and the output prints the variable as a floating-point number rounded to two decimal places.

Use Case #5: Store Data in a Variable

You can use the -v flag with printf to assign a shell variable and store data in this variable instead of printing it in standard output. Try these steps to see this idea in action:

  • Use the Vi (or your preferred editor) to create a bash script:

# vi variableexample.sh

  • Enter the following lines and save the script:

#!/bin/bash
printf -v var 'Welcome - Redswitches'
printf '%s\n' "$var"

In this script, printf -v var ‘Welcome – Redswitches’ assigns the string ‘Welcome – Redswitches’ to the variable var using the -v flag.

  • Lastly, execute the script:

# bash variableexample.sh

bash printf Store Data in a Variable

This command runs the script, and the output prints the contents of the stored variable.

Use Case #6: Convert Hexadecimal Numbers

To utilize the %d as a format specifier with printf to convert hexadecimal numerics to decimal ones, follow these steps:

# vi convert_hex_to_decimal.sh

  • Add these lines and save the script:

#!/bin/bash
printf 'Enter a hexadecimal number:\n'
read hexNumber
decimalNumber=$(printf "%d" "$hexNumber")
printf "Decimal equivalent: %d\n" "$decimalNumber"

In this script, %d in printf “%d” specifies that the command should treat the input variable hexNumber as a decimal (integer) number, effectively converting it from hexadecimal to decimal.

  • Execute the script:

# bash convert_hex_to_decimal.sh

Convert Hexadecimal Numbers

This command runs the script, prompting you to enter a hexadecimal number. The script then converts the input hexadecimal number to its decimal equivalent and prints the result.

Use Case #7: Convert Decimal Numerics to Octal

You can use the %o format specifier with printf command to convert decimal numbers to octal. Here are the steps:

# vi decimal_to_octal.sh

  • Add the following lines and save the script:

#!/bin/bash
printf "Enter a decimal number:\n"
read decimalNumber
octalNumber=$(printf "%o" "$decimalNumber")
printf "The octal representation of $decimalNumber is %o\n" "$decimalNumber"

In this script, %o in printf “%o” specifies the format to treat the input variable decimalNumber as an octal number, effectively converting it from decimal to octal.

  • It’s time to execute the script:

# bash decimal_to_octal.sh

decimal_to_octal bash printf

This command runs the script, prompting you to enter a decimal number. The script then converts the inputted decimal number to its octal equivalent and prints the result.

Use Case #8: Print Date Variable

To create a script that utilizes printf to display the current date and time, follow these steps:

  • Create a file for the bash script:

# vi current_datetime.sh

  • Add these lines and save the script:

#!/bin/bash
printf 'Today is %(%A, %B %d, %Y %T %p)T\n' -1

In this script, %A, %B %d, %Y %T %p in printf ‘%(%A, %B %d, %Y %T %p)T’ -1 specifies the format for the output consisting of the current date and time.

  • Execute the script:

bash current_datetime.sh

Print Date Variable bash printf

This command runs the script, and the output will display the current date and time.

Also Read: Get Current Date and Time in Python With 2 Easy Methods

Use Case #9: Add Commas to Thousands

To create a script that utilizes printf to add commas to thousands in numbers for improved readability, follow these steps:

# vi add_commas.sh

  • Add the following lines and save the script:

#!/bin/bash
printf "Enter a number:\n"
read number
printf "%'d\n" "$number"

In this script, %’d in printf “%’d” uses the  modifier to add commas to the output, denoting thousands for better readability.

  • Execute the script:

# bash add_commas.sh

bash printf script with add commas

 

 

 

 

This command runs the script, prompting you to enter a number. The script then adds commas to the input, automatically improving its readability.

Use Case #10: Get Character ASCII Code

To craft a script using printf to display the ASCII value of an input character, proceed with the following steps:

  • Create a bash script:

# vi character_ascii.sh

  • Add these lines and save the script:

#!/bin/bash
printf "Enter a character to get its ASCII code:\n"
read character
printf "ASCII code of '$character' is %d\n" "'$character"

In this script, %d in printf “%d” is used to output the ASCII value of the input character.

  • Execute the script:

# bash character_ascii.sh

bash printf Character ASCII Code

This command runs the script, prompting you to enter a character. The script then outputs the ASCII value of the entered character.

Also Read: How to Read Files Line by Line in a Bash Script [5 Simple Methods Inside!]

Conclusion

The printf command in a bash script provides a versatile and efficient way to format and display information.

Throughout this tutorial, we’ve delved into practical examples that showcase the flexibility and power of printf in various scenarios. From simple tasks like displaying text to more intricate formatting, this command proves to be a vital tool in Bash scripting.

RedSwitches offers the best dedicated server pricing and delivers instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQs

Q. Is printf better than the echo in Bash?

printf is often preferred over echo in Bash, especially for complex outputs, as it provides more control over formatting.

Q. Can printf output be colored?

Yes, printf can include ANSI color codes, allowing you to colorize text for more visually appealing outputs.

Q. How do I right-align text using printf?

To right-align text in printf, use a negative number in the format specifier, such as %-10s, which aligns the text to the right.

Q. Is Bash printf similar to C’s printf?

Yes, Bash printf is inspired by C’s printf and shares many similar formatting and conversion specifications.

Q. Can I use variables within format strings in printf?

Indeed, you can use variables within format strings in printf, ensuring proper referencing to incorporate dynamic content.

Q. How does the echo command differ from printf in Bash?

The echo command is more straightforward and commonly used for basic text output, while printf provides more advanced formatting options and precise control.

Q. What are special characters and escape sequences in Bash?

Special characters in Bash include characters with specific meanings, and escape sequences, like ‘\n’ for a newline, allow you to represent non-printable characters.

Q. How does the backspace character work in Bash?

The backspace character (\b) in Bash shifts the cursor one position backward, enabling the overwriting of the preceding character.

Q. When should I use single quotes in Bash?

Single quotes (‘ ‘) in Bash preserve the literal value of each character, making them helpful in preventing the interpretation of unique characters and variables.

Q. How are programming languages related to printf in Bash?

printf in Bash is inspired by the printf function in programming languages like C, providing a consistent way to format and output text.

Q. What is a conversion specification in printf?

In printf, a conversion specification (e.g., %d, %s) defines how an argument should be formatted and inserted into the output string.

Q. How do double quotes differ from single quotes in Bash?

Double quotes (” “) enable variable expansion and the interpretation of certain special characters, while single quotes (‘ ‘) maintain the literal value of each character.

Q: What can you do with the tab space in printf?

The tab space in printf (\t) can be used to create horizontal spacing, aligning text or data in columns for a more organized output.

Q. What does “character wide” mean in the context of printf?

“Character wide” refers to the width occupied by a single character in the printf output, and it can be adjusted using format specifiers to control the spacing.

Try this guide with our instant dedicated server for as low as 40 Euros