User Tools

Site Tools


bash:output:assign_output_of_shell_command_to_variable

BASH - Output - 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 =.

NOTE: The use of $(command) is not portable. This is BASH-only syntax. If you want portable write using backticks such as “`command`”.


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"
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

Use Multiline Command

Try the following syntax:

my_var=$(command \
arg1 \
arg2 \
arg3 )
echo "$my_var"

Example using Date

OUT=$(date \
--date='TZ="Europe/Jersey" 09:00 next Thu')
echo "$OUT"

Example using Ping

#!/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}"
bash/output/assign_output_of_shell_command_to_variable.txt · Last modified: 2021/01/26 14:24 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki