Bash Printf - How to Print a Variable in Bash


Printing variables in Bash is a common task when working with shell scripts. Bash printf command is a powerful tool that allows you to print variables with precision and formatting options. In this article, we will explore how to use Bash printf to print variables in various ways.

What is Bash Printf?

Bash printf is a command-line utility that is used to format and print text on terminal. It is a built-in command in Bash, which means that it is available in every Bash shell session without need for any external dependencies.

The printf command is similar to echo command, but it provides more control over output format. With printf, you can specify width, precision, and alignment of output. This makes printf a useful tool for printing variables in a specific format.

Printing a Variable

Printing a variable is a simple task in Bash. You can use echo command to print value of a variable on terminal. For example, if you have a variable called "name" that contains value "John," you can print value of variable with following command −

Example

name="John"
echo $name

Output

John

However, if you want more control over output format, you can use printf command.

Using Printf to Print a Variable

The syntax for using printf to print a variable is −

printf format-string variable

The "format-string" is a string that specifies format of output. "variable" is name of variable you want to print. Let's take a look at some examples.

Example 1: Printing a Variable Without any Formatting

In this example, we will use printf to print value of a variable without any formatting. We will use same variable "name" that we used in previous example.

name="John"
printf "%s
" $name

Output

John

In this example, we used "%s
" as format string. "%s" is a placeholder that is replaced with value of variable, and "
" is a newline character that adds a line break after output.

Example 2: Printing a Variable With Formatting Options

In this example, we will use printf to print value of a variable with formatting options. We will use variable "price" that contains a float value.

price=9.99
printf "The price is $%.2f
" $price

Output

The price is $9.99

In this example, we used "$%.2f
" as format string. "$" is a special character that indicates that output should be formatted as a currency. "%.2f" specifies that float value should be rounded to two decimal places. "
" adds a line break after output.

Example 3: Printing Multiple Variables with Formatting Options

In this example, we will use printf to print multiple variables with formatting options. We will use variables "name" and "age" to print a sentence.

name="John"
age=30
printf "My name is %s and I am %d years old.
" $name $age

Output

My name is John and I am 30 years old.

In this example, we used "%s" and "%d" as placeholders for "name" and "age" variables, respectively. "%s" is a placeholder for a string, and "%d" is a placeholder for an integer. "
" adds a line break after output.

Additional Examples

Let's take a look at some additional examples of using Bash printf to print variables −

Example 4: Printing a Variable with Leading Zeros

In some cases, you may need to print a number with leading zeros. For example, if you want to print current date and time in a specific format. You can use format string "%02d" to print an integer with leading zeros. number "2" specifies width of output, and "0" specifies that leading zeros should be added.

day=1
month=1
year=2023
printf "Today's date is %02d/%02d/%04d
" $day $month $year

Output

Today's date is 01/01/2023

Example 5: Printing a Variable as Binary or Hexadecimal

You can use format string "%b" to print an integer as binary or "%x" to print it as hexadecimal.

number=10
printf "Binary: %b
" $number printf "Hexadecimal: %x
" $number

Output

Binary: 10
Hexadecimal: a

Example 6: Printing a Variable as a Percentage

You can use format string "%.2f%%" to print a float value as a percentage with two decimal places.

discount=0.25
printf "Discount: %.2f%%
" $(echo "$discount * 100" | bc -l)

Output

Discount: 25.00%

In this example, we used bc command to calculate percentage by multiplying discount value by 100.

Formatting Options For Printf

In addition to examples we've already seen, there are many other formatting options you can use with printf. Let's take a look at some of most commonly used options.

Width and Alignment

You can specify width of output using syntax "%[width]s" or "%[width]d". For example, if you want to print a string with a width of 10 characters, you can use format string "%10s". If string is shorter than 10 characters, spaces will be added to left to make up width.

You can also specify alignment of output using "-" character. For example, if you want to print a string with a width of 10 characters aligned to left, you can use format string "%-10s".

Precision

You can specify precision of a float value using syntax "%.x", where "x" is number of decimal places you want to round to. For example, if you want to round a float value to two decimal places, you can use format string "%.2f".

Padding

You can add padding to output using syntax "%0[x]d" or "%0[x]s". For example, if you want to print an integer with a width of 5 characters and padded with zeros, you can use format string "%05d". number of zeros corresponds to width of output.

Common Mistakes to Avoid

When using Bash printf, there are some common mistakes that beginners often make. Here are a few things to keep in mind to avoid these mistakes −

Forgetting Format String

The most common mistake is forgetting to specify format string. If you don't include format string, printf will not know how to format output. For example, following command will produce an error −

Example

name="John"
printf $name

Output

John

To fix this, you need to include format string −

Example

name="John"
printf $name

Output

John

Using Wrong Format Specifier

Another common mistake is using wrong format specifier for variable type. If you use wrong specifier, output may be incorrect or produce an error. For example, if you use "%d" to print a string variable, output will be unexpected.

Not Escaping Special Characters

If you need to include special characters in output, such as tabs or newlines, you need to escape them. Otherwise, they may be interpreted by shell as commands or other special characters. For example, following command will not produce desired output −

Example

printf "Name:\tJohn
"

OutPut

Name:	John

To fix this, you need to escape tab and newline characters −

Example

printf "Name:\tJohn
"

Output

Name:	John

Conclusion

In this article, we've explored how to use Bash printf to print variables in various ways. We've seen how to print variables without any formatting, with formatting options, and multiple variables with formatting options. We've also looked at some of most commonly used formatting options for printf, such as width and alignment, precision, and padding.

By using Bash printf, you can print variables in a specific format that meets your needs. This makes printf a useful tool for shell scripting and other command-line tasks.

Updated on: 12-Apr-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements