Intro To 'printf' Command In Linux
2023-06-10 - By Robert Elder
I use the 'printf' command to print formatted strings:
printf '%s %i %u %%.\n' 'Hello World!' -1 1
Hello World! -1 1 %.
The 'printf' Function Vs. 'printf' Shell Command
The 'printf' command can be thought of as a thin wrapper around the 'printf' function from the C Standard Library.
The 'printf' command is capable of printing formatted strings of text in ways that are more advanced than the echo command:
printf 'First: %c Second: %d Third: %s.\n' 'p' 123 "Hello"
First: p Second: 123 Third: Hello.
The first argument to the 'printf' command is the format string to print, where the percentage signs indicate the location where arguments will be substituted. This is followed by zero or more arguments.
Example Format Strings With 'printf'
The 'printf' command supports floating point numbers with flags that control the format and precision:
printf "My favourite floating point number: '%.2f'.\n" 420.69
printf "My favourite floating point number: '%.10f'.\n" 420.69
My favourite floating point number: '420.69'.
My favourite floating point number: '420.6900000000'.
It also supports signed and unsigned integers:
printf "%u\n" -1
18446744073709551615
printf "%i\n" -1
-1
printf "0x%X\n" 3735928559
0xDEADBEEF
characters:
printf "My favourite octal characters: '%b' '%b' '%b'.\n" "\0141" "\0142" "\0143"
My favourite octal characters: 'a' 'b' 'c'.
strings:
printf "My favourite string: '%s'.\n" "Linux"
My favourite string: 'Linux'.
and many more.
Shell Builtin Vs. Executable
The 'printf' command can be implemented separately as a shell builtin or independently as a standalone application. Therefore, the exact behavior of the 'printf' command could depend on which version you end up using:
type -a printf
printf is a shell builtin
printf is /usr/bin/printf
printf is /bin/printf
See the 'info' pages for more information about the differences between the builtin and shell 'printf' functions:
info printf
...
Due to shell aliases and built-in ‘printf’ functions, using an
unadorned ‘printf’ interactively or in a script may get you different
functionality than that described here. Invoke it via ‘env’ (i.e., ‘env
printf ...’) to avoid interference from the shell.
...
And that's why the 'printf' command is my favourite Linux command.
Intro To 'stty' Command In Linux
Published 2023-10-04 |
$1.00 CAD |
Intro To 'nproc' Command In Linux
Published 2023-07-15 |
Intro To 'comm' Command In Linux
Published 2023-09-06 |
How To Force The 'true' Command To Return 'false'
Published 2023-07-09 |
A Surprisingly Common Mistake Involving Wildcards & The Find Command
Published 2020-01-21 |
A Guide to Recording 660FPS Video On A $6 Raspberry Pi Camera
Published 2019-08-01 |
Intro To 'chroot' Command In Linux
Published 2023-06-23 |
Join My Mailing List Privacy Policy |
Why Bother Subscribing?
|