Command Bash printf gives you better Terminal control and more formatting options than the echo command. So, in this article, I will show you how to use the Bash printf command on Linux.
Join the channel Telegram of the AnonyViet 👉 Link 👈 |
Printf on Terminal
This is one of the most basic parts of interacting with a program. The program writes something to the screen and you read it. Even considering the convention of command-line programs that originated in Unix and Linux, the more concise the better—many programs only log errors to the Terminal if something goes wrong. Telling the user what is happening, or is about to happen, or has just happened is an essential programming principle.
The bash shell has an echo command that can write text to Terminal. It can process variables and display their values if they are printed as strings and you can use it in scripts or on the command line. So why does printf exist? Does the Echo have problems writing text? Well, printf provides functions other than the simple act of writing a text string to Terminal. It allows you to format the output with great flexibility and it also has other uses.
The Bash printf command is emulated on the printf function from language C, but it’s still a little different. If you know C, you’ll need to notice those differences.
Writing Basic Strings
Let’s see how echo and printf are different when they print the strings to the terminal.
echo here are some words
printf here are some words
The echo command prints all words but printf only prints the first word. Also, no newlines are printed. The output is placed right on the command prompt. However, first thing, for printf to work with all words, you need to enclose the string in double quotes.
echo here are some words
printf "here are some words"
Printf printed all the words but we still don’t get newlines. That’s because with printf you only get a newline if you ask for it. That may sound like a con, but it lets you decide whether to add a newline or not. To make printf print a newline, you need to add “\n” to your string.
echo here are some words
printf "here are some words\n"
Sometimes you will use a newline and sometimes not. This is the case where one printf statement uses a newline and the other does not.
printf "How-To " && printf "Geek\n"
Because the first printf command does not print a newline, the output from the second printf is placed immediately after “How-To” and on the same line. The second printf uses \n to print a newline. This causes the command prompt to appear on the line below the printed text.
Other special characters
Here are some other special characters you can use like “\n”.
- \n: Create a new line.
- \r: Prints text to the beginning of the line and returns the cursor to the current position.
- \t: Print a tab character.
- \v: print vertical tab space.
- \\: Prints a backslash character.
- \”: Prints a double quote character.
- \b: Print spaces.
A newline escape character and returns the cursor to the current position.
printf "Honey is the root of all evil\rMoney\n"
The printf command processes its input from left to right. The string is printed as normal text until printf encounters the “\r” character. The output cursor is moved back to the beginning of the current line.
When the printf command encounters the “\r” character, it will print the text after the “\r” character, ie Money overwrites Honey and returns the cursor to the current position. That is, the cursor will now be at the end of the word evil.
Double quotes “”” are used to quote strings, and the backslash character “\” denotes plain text. If you want to print these characters, you need to remove them with a backslash. This causes printf to treat them as normal literal characters.
printf "This is a \tTab, this is a quotation mark \", and this \\ is a Backslash\n"
Using variables
Using variables with printf is very similar to echo. To include a variable, like this environment variable, precede it with the dollar sign “$” as usual.
printf "Home directory: $HOME\n"
String Format
String format is to define the output format of the string. You provide text and other values as arguments to format the string.
Format strings can include text, special character strings, and format codes. Format values tell printf the type of argument, such as string, integer, or character.
These are the most common formats. All of them are preceded by a percent sign “%”. To print the percentage sign, you use the two percent signs together “%%”.
- %s: Print a string.
- %c: Print a character.
- %d: Print an integer.
- %f: prints a real number.
- %u: Print an unsigned integer.
- %o: Prints a value in octal.
- %x: Prints a value in hexadecimal, in lowercase.
- %X: Prints a value in hexadecimal, in uppercase.
- %e: Prints a real number in scientific notation, in lowercase.
- %E: Prints a real number in scientific notation, in uppercase.
- %%: Prints the “%” percentage symbol.
printf "How-To %s\n" "Geek"
printf "%s%s %s\n" "How" "-To" "Geek"
The string format in the first command includes some text of its own. I pass the string “Geeks” as an argument to printf. It is printed in the format “%s”. Note that there is only one space between the format string and the argument. In C you need commas to separate them but with the Bash version of printf, using spaces is enough.
The second format string contains only the format codes and the new text string. The three string arguments are used by each word of the format “%s” in turn. Again, in C you need to put a comma between each argument but Bash printf lets us forget that.
To print different types of arguments, simply use the appropriate formatting tool. This is a fast numeric conversion built in printf. I will print the value 15 as decimal, octal and hexadecimal notation.
printf "Dec: %d\nOct: %o\nHex: %x\n" 15 15 15
Another less messy example.
printf "Hex: %x\n" 15
Most of us are used to seeing hexadecimal values in uppercase and with values less than 0x10 printed with leading zeros. We can do so by using the uppercase hexadecimal format code “%X” and placing a width specifier between the percent sign “%” and the character “X”.
This tells printf the width of the field in which the argument will be printed. This field is padded with spaces. With this format, two-digit values will be printed without any padding.
printf "Hex: %2X\n" 15
Now we get an uppercase value, printed with leading space. We can make printf print zeros instead of spaces by putting a zero in front of 2:
printf "Hex: %02X\n" 15
The precision specifier allows you to set the number of decimal points to print.
printf "Floating point: %08.3f\n" 9.243546
This makes it easy to create result tables with neatly aligned output. This next command also demonstrates one of the other quirks of Bash printf. If there are more arguments than the format number, the arguments will be included in the format string in order until all arguments are used up.
printf "Float: %8.3f\n" 9.243546 23.665 8.0021
You can also use characters that specify width and precision with strings. This command prints strings in a field 10 characters wide.
printf "%10s %d\n" "coats" 7 "shoes" 22 "Umbrellas" 3
By default, values are right aligned in their fields. To left-align them, use the minus sign “-” right after the percent sign “%”.
printf "%-10s %d" "coats" 7 "shoes" 22 "Umbrellas" 3
The precision specifier can be used to set the maximum number of characters to be printed. We are using the colon characters “:” to display the width of the field.
printf ":%10.6s:\n" "coats" "shoes" "Umbrellas"
printf ":%-10.6s:\n" "coats" "shoes" "Umbrellas"
The width parameter can even be passed in as an argument. Use an asterisk “*” instead of a numeric symbol and pass the width as an integer argument.
printf "%*s\n" 20 "Rightmost" 12 "Middle" 5 "leftmost"
Other tricks
Format specifiers inside the format string will work with the appropriate values, whether they are supplied on the command line as regular arguments or they are generated as the output of an expression.
This command prints the sum of two numbers:
printf "23+32=%d\n" $((23+32))
This command prints out the number of directories in the current working directory:
printf "There are %d directories\n" $(ls -d */ | wc -l)
This printf command prints a string returned from another command.
printf "Current user: %s\n" $(whoami)
If the string format code “%s” is not supplied with an argument, printf will not print.
printf "One: %s two: %s\n" "Alpha"
If the string format code “%s” is given a numeric value, it will still print the number.
printf "One: %s two: %s\n" "Alpha" 777
If the integer format code “%d” receives no arguments, it prints 0.
printf "Integer: %d\n"
If an integer format “%d” receives a string argument, Bash will print an error message and printf will print 0.
printf "Integer: %d\n" "Seven"
Confusing symbols can be created using Unicode or their “code point”. They are created with the letter “u” followed by their Unicode value.
printf "The Euro symbol: \u20AC\n"
To include the escape sequence in the argument string, you must use the “%b” format specifier in the format string, not the “%s” string formatter.
printf "%s" "\u20AC\n"
printf "%b" "\u20AC\n"
The first printf statement does not handle Unicode values and it does not recognize the newline character. The second printf statement uses the format code “%b”. This correctly handles the Unicode character and a printed newline.