ubuntu:bash:assign_output_of_shell_command_to_variable
This is an old revision of the document!
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: <code bash> 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
ubuntu/bash/assign_output_of_shell_command_to_variable.1574982568.txt.gz ยท Last modified: 2020/07/15 09:30 (external edit)