To assign output of any shell command to variable in bash, use the following command substitution syntax:
var=$(command-name-here) var=$(command-name-here arg1) var=$(/path/to/command) var=$(/path/to/command arg1 arg2)
…or use backticks based syntax as follows to assign output of a Linux command to a variable:
var=`command-name-here` var=`command-name-here arg1` var=`/path/to/command` var=`/path/to/command arg1 arg2`
Do not put any spaces after the equals sign and command must be on right side of =.
NOTE: The use of $(command) is not portable. This is BASH-only syntax. If you want portable write using backticks such as “`command`”.
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" printf "%s\n" "$now"
returns:
Wed Apr 25 00:55:45 IST 2012
You can combine the echo command and shell variables as follows:
echo "Today is $now"
returns:
Today is Wed Apr 25 00:55:45 IST 2012
You can do command substitution in an echo command itself (no need to use shell variable):
echo "Today is $(date)" printf "Today is %s\n" "$(date)"
returns:
Today is Wed Apr 25 00:57:58 IST 2011
Try the following syntax:
my_var=$(command \ arg1 \ arg2 \ arg3 ) echo "$my_var"
OUT=$(date \ --date='TZ="Europe/Jersey" 09:00 next Thu') echo "$OUT"
#!/bin/bash _ping="/bin/ping" domain="www.sharewiz.net" ping_avg="$(${_ping} \ -q \ -c 4 \ ${domain} | grep rtt)" echo "Avg ping time for ${domain} : ${ping_avg}"