Skip to main content

To assign the output of a shell command to a Shell variable under Unix like operating system, you use a feature called command substitution.

# -----------------------------------------------------------------------------
# Bash: Assign Output of Shell Command To Variable
#   http://www.cyberciti.biz/faq/unix-linux-bsd-appleosx-bash-assign-variable-command-output/
# -----------------------------------------------------------------------------

# SYNTAX

var=$(command-name-here)
var=$(command-name-here arg1)
var=$(/path/to/command)
var=$(/path/to/command arg1 arg2)

# OR

var=`command-name-here`
var=`command-name-here arg1`
var=`/path/to/command`
var=`/path/to/command arg1 arg2`

##
# EXAMPLE
# To store date command output to a variable called now, enter:
##

now=$(date)

# OR

now=`date`

# To display back result (or output stored in a variable called $now)
# use the echo or printf command:

echo "$now"

# OR

printf "%sn" "$now"
# Wed Apr 25 00:55:45 IST 2012

You can combine the echo command and shell variables as follows:

echo "Today is $now"
# Today is Wed Apr 25 00:55:45 IST 2012