Linux / Unix: Bash Shell Assign Printf Result To Variable

Posted on in Categories last updated August 29, 2012

How do I assign printf command result to a shell variable under Unix like operating systems?

The printf command syntax is as follows:

printf "FORMAT" var
var=$(printf "FORMAT" var1)
var="$(printf "FORMAT" var1)"

Examples

Type the following command:

dir="/home/httpd" 
printf "%s\n" $dir

To store result to a variable called j, enter:

dir="/home/httpd" 
j=$(printf "%s" $dir)
echo "$j"
printf "%s\n" $j

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Leave a Comment