The “printf” Command in Linux [8 Practical Examples]

The “printf” is a command line-based utility in Linux that formats and prints arguments under the control of the format. The main purpose of “printf” is to write formatted output. In addition to the standard format specifications, the “printf” command interprets to expand backslash escape sequences, quote the argument in a way that can be reused as shell input, and output the date-time string.

In this article, you will learn to print formatted text and control precisely how to display information on your terminal with 8 practical examples using the “printf” command in Linux.

Syntax of “printf” Command in Linux

The basic syntax of the “printf” command is as follows:

printf [-v var] FORMAT [arguments]
EXPLANATION:
  • The options [-v var] assign the output to the shell variable VAR rather than display it on the standard output.
  • The FORMAT is a character string that contains three types of objects: plain characters, which are simply copied to the standard output; character escape sequences, which are converted and copied to the standard output; and format specifications, each of which causes printing of the next successive.
  • The [arguments] field refers to the formatted output based on the given formats.

Options of “printf” command in Linux

The “printf” command in Linux has only two options: -version and -help. These two options show the information related to the “printf” command and do not participate in function and formatting output with the “printf” command.

Here are the options of the “printf” command in Linux:

Option Function
-version Provides the current version information of the printf command.
-help Shows the help menu of the printf command.

Format Specifiers of  “printf” Command in Linux

The format specifier is a string that defines the arguments and way of formatting specifiers. Here is a list of some common format specifiers of the “printf” command with their functionalities:

Specifier Function
%s Reads the input as a string of characters.
%b Same as the string specifier but uses the argument to interpret escape sequences.
%d Shows the integral values.
%x Shows the hexadecimal values.
%f Shows the floating values.

How to Use “printf” Command in Linux

To use the “printf” command in Linux, use the following steps:

  1. Open your terminal.
  2. Write the following command and press ENTER:
    printf "Hello, Linux.\n"

    Using printf command to print formatted text

    Upon execution, the “printf” command prints the formatted text to your terminal.

8 Examples of Using “printf” command in Linux

Here are a few cases where you can use the printf command in your Linux distribution:

1. Printing String Output

To print a specified string output, use the printf command followed by %s string specifier. A string is a sequence of characters that represent texts.

Here is the command to print a string output with a specified variable:

printf "Hello, This is %s.\n" $LOGNAME

Printing string output with %s specifier

This command prints the string output by replacing the string specifier (%s) with the variable name.

2. Interpreting Escape Sequences

You can interpret an escape sequence with a given argument, using the printf command with the %b specifier. The “%b” specifier is similar to the “%s” specifier except it allows us to interpret escape sequences. For example, to read backlashes for escape sequence interpretations use the below command:

printf "Hello, \nThis \nis \n%b.\n" $LOGNAME

Interpreting escape sequences with %b specifier

As a result, the “printf” command with %b specifier prints the string output with appropriate newlines and interpretation of escape sequences.

Here are a few examples of escape sequences:

Item Function
\\ Backslash
\t Tab
\a Alert
\b Backspace
\f Form feed

3. Formatting Numeric Values

To format numeric values, you can use the printf command. Here are a few cases:

3.1 Integer Values

To format and print integer values, use the printf command followed by the %d specifiers. The “%d” is an integer specifier that shows the integral values.

Here is the command to print integers from different given number formats:

printf "%d\n" 123 0x7B 0173 123.00

Printing integer number using %d specifier with printf

The command formats and prints integer numbers from different number formats in separate lines.

3.2 Float Values

To print float values, you can apply the printf command with the %f specifier. The “%f” is a float specifier that prints numbers up to 6 points by default. For example, to format and print numbers to float numbers, use the below command:

printf "%f\n" 123 0x7B 0173 123.00

Using %f specifier with printf command to display float values

As you can see, the command treats different number representations as floating numbers and adds floating points up to 6. However, you can limit the decimal places to a certain point using the "%.<num>f" specifier. Where, <num> is the number of float points you wish to see. For example:

Here is the command to limit the floating points to 2 points using a “printf” specifier:

printf "%.2f\n" 123 0x7B 0173 123.0

Limiting float values to 2 points using %.2f specifier with printf

See from the image, the command formats and prints floating numbers up to 2 points.

3.3 Hexa Decimal Values

To format and print the hexadecimal values, use the printf command along with the %X or %x specifiers. The “%X” and “%x” are hexadecimal specifiers that print the hexadecimal numbers in upper and lower cases respectively.

Here is the command to print hexadecimal numbers in upper cases:

printf "%X\n" 123 0xff 0277

Using printf and %X specifier to print hexadecimal values in uppercase

Hence, the command converts different number representations and prints them in hexadecimal numbers in upper cases.

To format and print hexadecimal numbers in lower cases, run this command below:

printf "%x\n" 123 0xff 0277

Printing hexadecimal values in lower case using printf with %x specifier

In output, you get the hexadecimal in lower cases.

4. Printing Environmental Variables

To print the value of a specific environmental variable, you can use the printf command. Here is the command:

printf "%b\n" "My shell is: "$SHELL

Using printf with %b to print current running shell

The command shows the value of the SHELL environmental variable for the specific user.

5. Printing Date and Time

To print the current date and time, you can again use the printf command along with the date command:

today="$(date)"
printf "The current date & time is: %s\n" "$today"
EXPLANATION

Here, today="$(date)" assigns the current date and time to a variable using the date command. And, printf "The current date & time is: %s\n" "$today" prints the current date and time using printf, where “%s” is replaced by the value stored in the variable.

Assigning date command in a variable and printing date and time with printf

6. Adding Two Numbers

To manually add two numbers you can use the printf command. Here is an example:

printf "200+55=%d\n" $((200+55))

Adding two numbers with printf command

See the command calculates the sum of two numbers using an arithmetic expression.

7. Printing Number of Directories

To print the total number of directories in the current directory, use the printf command with ls and wc command. Here is the combined command:

printf "Total directories are: %d\n" $(ls -d */ | wc -l)
EXPLANATION

Here, the “printf” displays the total number of directories in the current directory.  The command part ls -d */ lists all the current directories and wc -l counts them. The “printf” substitutes the count into the format string to output the total.

Combining printf, ws and ls commands to get total number of directories

Subsequently, you get the total number of directories in your current directory.

8. Printing Symbols

To print Unicode symbols, you can use the printf command. For example, to print the Celsius degree symbol (℃), use the command:

temperature=20
printf "Current temperature: %d\u2102\n" "$temperature"

Printing Unicode symbols using printf command

Consequently, the command prints the Celsius degree symbol using the given Unicode character.

Conclusion

In summary, the “printf” command allows you to print string output, environmental variables, date/time, and format numbers, etc. You can also combine the command with its format specifiers, escape sequences, and other commands to create custom output, format data for reports, etc. For any suggestions or feedback, please don’t hesitate to reach us through the comment box.

People Also Ask

What is “printf” in Linux?

The “printf” is a command line-based utility in Linux that formats and prints arguments under the control of the format. The main purpose of “printf” is to write formatted output. It is like the printf() function in the C programming language, where a format string is given to a set of arguments to return specific output.

Can we use “printf” in shell script?

Yes, you can use the “printf” command in the shell script. Bash “printf” allows printing text on a terminal with various formatting options. It’s particularly useful for printing in a shell script to display data in a specific format. You can also use it directly on the command line for quick output formatting.

What is the difference between “printf” of bash shell, and /usr/bin/printf?

The main difference is that the bash built-in “printf” supports the %q format specifier, which prints escape symbols alongside characters for safe shell input, while /usr/bin/printf does not support %q.

In which case should I use “printf” command instead of echo command in Linux?

Instead of echo, you should use the printf command if you want to print formatted output. The echo command is useful for basic text output, while “printf” controls the output formatting more precisely.

Can “printf” command print to a file at the same line in Linux shell bash script?

Yes, the “printf” command can print to a file on the same line in a Linux shell bash script. You just redirect the output of printf to the file using the append redirection (>>) operator. Here’s an example: printf "Hello, Linux" >> output.txt. This command will print the text to the file without moving to the next line.

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Avatar photo

Yousuf Shovon is a Linux Content Developer Executive (LCDE) at SOFTEKO. Previously, he worked for ExcelDemy, writing over 60+ articles on Excel. His goal is to write quality content for users to read and learn. In the future, he also wants to build various projects with LinuxSimply. He completed his graduation and post-graduation in Information Technology from Jahangirnagar University. Yousuf finds joy in solving diverse Linux-related problems to gain an all-around experience in Linux. Read Full Bio

Leave a Comment