Linux Bash Shell Printf Command Examples
Linux provides different commands to print given string or data into the terminla or specified place.
printf is one of them which is similar to the C programming language
printf() function. Actually it is cloned from C
printf function which provides similar features to write given string to the terminal in a structured manner.
We will start by printing help information about
printf . And as we will examine most of the options provided by
printf in the next part of the tutorial.
$ man printf
We will start by simply printing given string. We will provide the string we want to print in a double quote. In this example we will print
hi poftut .
$ printf "hi poftut"
We can use
%s in order to provide external strings to the given string. External strings will be added to the
%s place. In this example we will provide
poftut as external string.
$ printf "hi %s" "poftut"
Multiple String Format
We can also provide multiple external string which will cause multiple print like a loop.
$ printf "hi %s" "poftut" "ismail"
Because we use double quote in shell we need to have some special mechanism in order to print double quotes in string. We will use
\" to print double quote properly.
$ printf “hi \”ismail\” ”
As backslash is used as a helper we can use
\\ as backslash like below.
$ printf “hi \ismail ”
If given terminal supports sound we can play a ping sound with
\a which is named alert.
$ printf "hi \a ismail "
Backspace is used to delete previously given string. We will use
\b to specify backspace. In this example
hi will be deleted with two backspace.
$ printf "hi\b\bismail"
No Further Output
We can stop output at the given position of the string we will use
\c which is shortcut for cancel. In this example we will cut output after
$ printf "hi \c ismail"
We can use
\e for a escape secuence.
$ printf "hi \e ismail"
As we have all ready see that after the end of the string there is no new line which will cause terminal start to print to the same line of the string. We can use
\n as new line which will start new line.
$ printf "hi \nismail \n"
We can use
\r for carriage return key.
$ printf "hi \rismail"
Tabs provides some space between given position. Horizontal tab is used to place spaces in horizontal manner.
$ printf "hi \tismail"
Vertical tab will place a tab in a vertical manner which will put given string to the next line.
$ printf "hi \vismail"
Print Decimal Format
We can print given hex or octal value in decimal format with
%d . In this example we will print hex number
0xF in decimal.
$ printf "Number is %d \n" 0xF
Print Hexadecimal Format
We can also print in Hex or Hexadecimal format with
%X .We will also add
0x for prefix.
$ printf "Number is 0x%X \n" 15
Print Octal Format
Octal format is used in 8 numbering system. We can use
%o to print in octal format like below.
$ printf "Number is %o \n" 15