This is an old revision of the document!
Table of Contents
Ubuntu - BASH - Assign Output of Shell Command To Variable
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 =.
Examples
To store date command output to a variable called now, enter:
## store date command output to $now ##
now=$(date)
OR
## alternate syntax ##
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"
Sample outputs:
Wed Apr 25 00:55:45 IST 2012
You can combine the echo command and shell variables as follows:
echo "Today is $now"
Sample outputs:
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)"
Sample outputs:
Today is Wed Apr 25 00:57:58 IST 2011
Use Multiline Command
Try the following syntax:
my_var=$(command \ arg1 \ arg2 \ arg3 ) echo "$my_var" ---- ===== Example using Date ===== <code bash> OUT=$(date \ --date='TZ="America/Los_Angeles" 09:00 next Thu') echo "$OUT" <code bash> ---- ===== Example using Ping ===== <code bash> #!/bin/bash _ping="/bin/ping" domain="www.cyberciti.biz" ping_avg="$(${_ping} \ -q \ -c 4 \ ${domain} | grep rtt)" echo "Avg ping time for ${domain} : ${ping_avg}"