Printf Command in Linux

FREE Online Courses: Knowledge Awaits – Click for Free Access!

In this article, we will learn everything about the printf command in Linux. We will look at what the printf command is, why it is used, the syntax of the printf command, the escape sequences used along with it, and the type conversion examples along with some examples to understand them better.

In the end, we will also look at some practical examples of the printf command in both shell programs and the terminal of ubuntu 20.04 to understand the printf command and the escape sequences and type conversions used along with it.

What is the printf command?

Printf is a command-line-based utility in Linux-based operating systems that helps print regular statements and variables like float, strings, integers, boolean, and many more. In simple words, the printf command works the same way it does in the C programming language.

The printf command is very famous in the C programming language. However, even in Linux-based operating systems, it works exactly like in C. You might wonder if the Linux terminal already has the echo command, then why the printf command?

Well, printf offers functionality beyond the simple act of writing strings to terminal windows. The printf command allows you to format the output with great flexibility and has many tricks up its sleeves.

Syntax of the printf command

The syntax of the printf command might look slightly intimidating at first, but when we understand the fields in the syntax, it will become a cakewalk. The syntax of the printf command is:

printf <options> <format> <arguments>

Let us take a closer look at the options present in the syntax of the printf syntax:

1. <options>

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

This field takes in 2 options: “–version” and “–help.”

2. <format>

This field controls the output and defines how the arguments will be expressed in the output.

3. <arguments>

This field takes in arguments that will be inserted into the formatted output according to the definition of format.

Options used with linux printf command

Unlike most of the commands in Linux, the printf command has only two options used along with it! The best part is that these options provide information regarding the printf command and have nothing to do with the function and formatting of the output of the printf command. Let us look at these two options in brief:

1. –version

It prints the information about the version of the printf command you are using in your systems, as shown below:

2. –help

This option prints out the help menu of the printf command as shown:

help

Escape sequences used with the printf command

Say you want to print multiple lines using the printf command. You simply can’t do it by pressing the enter button. Instead, you have to use the escape sequence “/n”. The escape sequences allow us to perform various tasks like giving tab space, backspace, vertical tab, and many more. Let us look at the escape sequences that are available with the printf command:

1. \\

This escape sequence lets you print a literal backslash (\) in your text.

2. \a

This escape sequence gives you an alert (the BELL character)

3. \b

This escape sequence stands for a backspace.

4. \c

This escape sequence produces no further output after this.

5. \e

This escape sequence stands for escape (Esc).

6. \f

This escape sequence gives a form feed.

7. \n

This escape sequence gives a new line. It means the text after this will appear in a new line and not in the same line before it.

8. \r

This escape sequence gives a carriage return.

9. \t

This escape sequence prints a horizontal tab (4 spaces).

10. \v

This escape sequence prints a vertical tab (4 lines).

11. \”

This escape sequence lets you print a literal double quote (“) in your text.

11. \<nnn>

This escape sequence is a byte with the octal value of the specified value “nnn”.

12. \x<hh>

This escape sequence is a byte with the hexadecimal value of the specified value “hh.”

13. \u<hhhh>

This escape sequence prints the Unicode character with a hexadecimal value of the specified value “hhhh.”

14. \u<hhhhhhhh>

This escape sequence prints the Unicode character with a hexadecimal value of the specified value “hhhhhhhh.”

Format specifier used with the printf command

As we saw above, it defines how the arguments will be expressed in the output. By definition, format specifiers are strings that determine the methods of formatting specifiers. Let us look at all of the format specifiers used along with the printf command:

1. %c

This format specifier treats the arguments as a single character.

2. %d

This format specifier treats the input as a decimal number.

3. %e

This format specifier treats the input as an exponential floating-point number.

4. %f

This format specifier treats the input as a floating-point number.

5. %i

This format specifier treats the input as an integer number.

6. %o

This format specifier treats the input as an octal number.

7. %s

This format specifier treats the input as a string of characters.

8. %u

This format specifier treats the input as an unsigned decimal number.

9. %x

This format specifier treats the input as a hexadecimal number.

10. %%

This format specifier prints a percentage sign

11. %Wd

This format specifier prints W integer X digits wide.

Type conversions

Before we look at the type conversions that we use with the printf command, let’s first explore the concept of explicit type conversions.

Say you want to change one data type to another, like from int to string, float to boolean, a string to float, etc., it sounds quite impossible initially, but this is the exact scenario where type conversions are used.

Type conversions are of 2 types, implicit and explicit. The compiler does implicit type conversions when operands are of different data types. The user does explicit type conversion by using operators. We make use of the format specifier to perform explicit type conversions.

Let us look at some examples of string type conversions by taking our input argument string as “DataFlair”:

FORMAT STRINGINPUT STRINGOUTPUT STRING
“%s”DataFlair“DataFlair”
“%4s”DataFlair“DataFlair”
“%.4s”DataFlair“Data”
“%-5s”DataFlair“DataFlair”
“%-15s”DataFlair“DataFlair ”
“%15.4s”DataFlair“ Data”
“%-15.4”DataFlair“Data ”
“%-15.2”DataFlair“Da ”

You must note that the printf command requires the number of conversion strings to match the number of arguments as it maps them one-to-one. Therefore, the number of formats must equal the number of arguments.

Now that we are done with the basics and theory of the finger command let’s look at some cool practical commands of the finger command by pairing it with escape sequences and format specifiers to understand their function better.

Printing “Hello world”

It would be a shame if we looked at other examples of the printf command without printing the cliched “Hello world” statement. Jokes apart, to print anything with the printf command, execute the print f command followed by the line you want to print enclosed in double-quotes as shown:

printf "<argument>"

hello world

If you notice the first output in the screenshot shown above, you will notice that after successfully printing the statement “Hello World”, the command prompt came on the same line instead of going on to the next line. To avoid this, use the escape sequence “\n” to send the command prompt to the next line.

Printing a variable

The printf command is most frequently used in programs, and we all know that programs contain a lot of variables, but how do we print variables using the printf statement? Well, we enclose the variable name in double quotes. You must note that while writing the variable name in the printf command, you must always precede it with a dollar sign ($) as shown:

printf "$<variable name>"

printing variable

Printing multiple variables

Using the method shown above, we can also print multiple variables. For this example, let us take the help of a small shell program that asks for the user’s first and last names separately and combines them:

printing multiple variables

The output of the shell program shown above will be as follows:

output of multiple variables

Printing a variable in a mock table

We can print a variable in a table by automatically adding dynamic padding or changing the variable output alignment using the printf command as shown:

printf '|%10s|\n' "$<variable name>"

variable in mock table

Notice that the word hello is left-aligned in the cell. If you want to make it right-aligned, use a minus symbol “-” after the percentage symbol (%) as shown:

printf '|%-10s|\n' "$<variable name>."

mock table right aligned

Adding decimal points

We saw above that using the format specifier “%s” followed by a set of numbers can alter the word “DataFlair”. Similarly, we can use the format specifier “%f” for numbers. Here is an example:

The shell program shown below asks the user to enter a decimal number and then reads and stores this number into the variable “number” and finally prints it by altering it slightly.

adding decimal points input

The sentence printf “%5.2f\n” “$number” says that the number must have a total of 5 numbers and only 2 numbers after the decimal point. So this is how we get the output:

adding decimal points

Storing data in a variable using the printf statement

Did you know we could also store the data in a variable using the printf command? It turns out that you can do the same by using the option “-v” followed by the variable name and then the value you want to store in it as shown:

printf -v <variable name> '<value>.'

storing data in variable

Converting a hexadecimal number to an integer

Here is a perfect example of type conversion: with the printf statement’s help and its format specifiers, we will convert hexadecimal numbers to normal integers. The shell program shown below asks the user to input a hexadecimal number, reads and stores the input into the variable name “number”, and finally converts it to an integer:

hexadecimal to integer

The statement [printf “%d\n” “$number”] converts the hexadecimal number into an integer as shown in the output below:

hexadecimal

Converting decimal numbers to octal

Here is another example of the type conversion: the shell program shown below asks the user to input a decimal number, reads and stores the input into the variable name “number”, and finally converts it to octal form:

decimal to octal

The statement {printf “The octal number of “$number” is %o\n” “$number”} converts the decimal number into its octal form as shown in the output below:

decimal to octal output

Printing today’s date with the printf command

Use the command shown below to print today’s date by using the printf command:

printf 'Today’s date is %(%F)T\n' -1

The format specifier “%F” treats the input as a floating-point number, and “-1” indicates the current date.

today date

Adding commas to numbers

We all add commas to a number for every three places from the unit place to make the number reading easier. We can do the same using the printf command by using the modifier (‘) as shown below:

printf "%'d\n" $<variable name>

Here is a shell program that makes use of the printf statement shown above:

commas to numbers

Just like we expected, we get the output with command separating thousands as shown below:

adding commas

Obtaining the ASCII code for a character

Follows the shell program shown below to obtain the ASCII code for a character:

ascii code for character

Upon execution of the shell program shown above, we get the following output:

ascii for character output

Exploring escape sequences

To get a better understanding of the escape sequences, here is an example using 4 escape sequences:

printf "Thus is a \tTab, this is a quotation mark \", and this \\ is a Backslash\rThis\n"

escape sequences

Tricks and quirks of the printf command

The printf command is far superior to the echo command. Let us look at some of them.

Directly adding two numbers using the printf command

We can directly add two numbers by using the command shown below:

printf "20+10=%d\n" $((20+10))

adding two numbers

Printing the number of directories using the printf command

By now, I hope you know that we can count the number of files by combining the ls command and the wc command as “ls | wc -l”, similarly we can count only the number of directories by using the command “ls -d */ | wc -l”. This command will only show the number and no text preceding it. However, If you combine this command with the printf command, as shown below, you can print any text you want:

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

number of directories

Printing the current user

Like this, we can continue pairing the printf command with many other commands. Another example is to pair the printf command with the whoami command and print the current user as shown below:

printf "The current user is %s\n" $(whoami)

current user

Printing the Euro (€) symbol

We print special symbols using their Unicode number or “code point”. The Unicode value of the Euro symbol is “20AC” you can use the format specifier “\u” as shown below:

printf "Euro symbol: \u20AC\n"

euro symbol

Summary

As you have seen, the printf command is a simple yet advanced and complicated tool with a lot of tips and tricks. The functionality of the printf command is really simple – printing stuff, but we all know that it is far deeper! Combine the printf command with the format specifiers, escape sequences, and other commands, and it opens the doors to a whole new world.

You have now understood what the printf command is, why it is used, the syntax of the printf command, the options, escape sequences, format specifiers, and type conversions used along with the printf command. You have also seen more than 15 examples of the printf command, where we used both in the terminal and shell programs by combining it with different commands, format specifiers, and escape sequences.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

follow dataflair on YouTube

Leave a Reply

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