Bash: Assign Output of Shell Command To Variable
You need to use command substitution feature of bash. It allows you to run a shell command and store its output to a variable. To assign output of any shell command to variable in bash, use the following command substitution syntax:
Tutorial details | |
---|---|
Difficulty | Easy (rss) |
Root privileges | No |
Requirements | Bash |
Estimated completion time | 2m |
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`
Do not put any spaces after the equals sign and command must be on right side of =. See how to assign values to shell variables for more information.
Examples
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 "%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)"
OR
printf "Today is %s\n" "$(date)"
Sample outputs:
Today is Wed Apr 25 00:57:58 IST 2011
0 comentarios:
Publicar un comentario
Suscribirse a Enviar comentarios [Atom]
<< Inicio