Printf command

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search

The printf builtin is used to print formatted text on the screen. Please see how to use printf command. Format and print data as per given FORMAT.


The syntax is

printf "FORMAT" variable
printf [options] "FORMAT" variable


printf command format and display data on screen. However, printf does not provide a new line. You need to provide format string using % directives and escapes to format numeric and string arguments in a way that is mostly similar to the C printf() function. Use printf to generate formatted output. For example print $USER variable:

printf "%s\n" $USER

# define foo and print it
foo="This is a test"
printf "%s\n" $foo

# define foo and print it but note $foo enclosed in ""
foo="This is a test"
printf "%s\n" "$foo"

# define bar and print it
printf "%d\n" $bar

How to assign the output to shell variable foo

Pass the -v var option to the printf command to assign the output to shell variable VAR rather than display it on the standard output/screen. The syntax is:

printf -v VAR "FORMAT" variable

For example:

printf -v foo "%s" "$bar"
printf "Value of foo is \"%s\"\n" $foo

A note about printf version

Please note that your shell may have its own version of printf, which usually supersedes the version described here. Find out if printf is an internal or external command using the type or command command:

type -a printf

Sample outputs:

printf is a shell builtin
printf is /usr/bin/printf

Getting help about printf shell builtin

help printf

Getting help about /usr/bin/printf external command

man 1 printf