Bash Assign Output of Shell Command To Variable

How do I assign the output of a shell command to a shell variable under Unix like operating system? For example, I want to store the date command output to a variable called $now. How do you do that? How can I set a variable to the output of a command in Bash?

You need to use command substitution feature of bash. It allows you to run a shell command and store its output to a bash variable.

ADVERTISEMENTS

Bash Assign Output of Shell Command To And Store To a Variable

To assign output of any shell command to variable in bash, use the following command substitution syntax:

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsBash
Time2m
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 =. See how to assign values to shell variables for more information.

Examples

Let us see some common examples for Linux, macOS, *BSD and Unix-like systems running bash.

BASH command output to the variable

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

How to use multiline command

Try the following syntax:
my_var=$(command \
arg1 \
arg2 \
arg3 )
echo "$my_var"

For example,

## date example ##
OUT=$(date \
--date='TZ="America/Los_Angeles" 09:00 next Thu')
echo "$OUT"

Another ping command example for you:

#!/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}"
Unix or Linux Bash Assign Output of a Shell Command To a Variable

Various ways to assign the output of a command to a shell variable

Conclusion

You learned how to assign output of a Linux and Unix command to a bash shell variable. For more information see GNU bash command man page here and read the following docs:

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
Network Utilitiesdig host ip nmap
Package Managerapk apt
Processes Managementbg chroot disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w

ADVERTISEMENTS
21 comments… add one
  • John Eisenhower Apr 25, 2012 @ 22:56

    They might want to add it .bash_profile so it is persistent across reboots. Such as;

    $ cat ~/.bash_profile
    alias ll=’ls -l’
    alias now=’date +%H:%M’
    $ now
    18:55

  • Chris F.A. Johnson May 4, 2012 @ 17:31

    Error: printf “%s\n” now

    Should be: printf “%s\n” “$now”

  • Amit Jun 12, 2013 @ 12:02

    i m trying to kill a process running on port say 4723…by using command “kill `lsof -t -i:4723`”…..it works fine..but i need to pass variable in lsof command instead of giving directly 4723…like..

    var number = 4723;
    “kill `lsof -t -i:number`”
    is it possible…? and how..plz replyyy soon..thanks in advance

    Amit

  • Ahmed Samir Jul 19, 2013 @ 13:59

    this is very helpful thank you

  • Charly Aug 11, 2013 @ 6:55

    What about Piped command like
    this?
    ie.
    droppedbyte=(iptables -L -v -n –line-number |grep DROP| awk ‘$1 = 5 {print $3}’)
    or
    droppedbyte=`iptables -L -v -n –line-number |grep DROP| awk ‘$1 = 5 {print $3}’`
    Fail :(

    -bash: syntax error near unexpected token `|’

    This isn’t working because i used this “|”, need help

    • 🐧 nixCraft Aug 11, 2013 @ 7:41

      Try

      droppedbyte="$(iptables -L -v -n --line-number | grep DROP | awk '$1 = 5 {print $3}')"
      echo "$droppedbyte"
      • Charly Aug 11, 2013 @ 8:28

        you are awesome :D

        This also worked.
        droppedbyte=`iptables -L -v -n –line-number |grep DROP| awk ‘$1 = 5 {print $3}’`

      • Vimjob Oct 30, 2013 @ 3:41

        Total shot in the dark Google search landed me here and this thing worked! Thanks a TON!

  • MattS Sep 30, 2013 @ 22:04

    Thanks nixCraft — You just saved me a lot of time.

  • vignesh Jan 23, 2014 @ 17:59

    Hi,

    Am stuck in a shell script that stores a value recrusively when it runs to a variable.
    when am running manually the value get stores but in crontab its not getting store.
    please help me in this, below is my script.

    #!/bin/ksh
    
    rm /u01/oracle/sba81/nas_siebel_fs_prd1/Interfaces/Meridio/Outbound/out.csv
    
    a=`ls -lad /u01/oracle/sba81/nas_siebel_fs_prd1/Interfaces/Meridio/Outbound/Archive | head -1 | awk -F" " '{print $5}'`
    
    #echo "$a" >> /u01/oracle/sba81/nas_siebel_fs_prd1/Interfaces/Meridio/Outbound/out.csv
    
    #a=`cat size.txt | head -1 | tail -1 | awk -F"|" '{print $1}'`
    b=`$c`
    
    echo "$a,$c" >> /u01/oracle/sba81/nas_siebel_fs_prd1/Interfaces/Meridio/Outbound/out.csv
    
    if [ "$a" = "$b" ]
    then
     echo "Meridio Interface stuck=$a" >> /u01/oracle/sba81/nas_siebel_fs_prd1/Interfaces/Meridio/Outbound/output.csv
     cat /u01/oracle/sba81/nas_siebel_fs_prd1/Interfaces/Meridio/Outbound/output.csv | mailx -s "Meridio Interface Down" email1 email2 email3
     c=`$a`
    else
     c=`$a`
    fi
    
  • romain Jun 20, 2014 @ 11:03

    Simple, concise, straighforward… excellent tutorial !

    Many thanks!

  • mo Sep 24, 2014 @ 0:40

    Many thanks… also saved me quite a bit of time !!

  • runej Dec 21, 2014 @ 18:43

    > var number = 4723;
    >

    varprt=4723 && lsofout=$(lsof -t -i:$varprt) && pidout=$(pidof $lsofout) && kill $pidout

    ???

  • Andy McPob Apr 8, 2015 @ 14:07

    Hi, can you assist ?

    i’m trying to run the command softwareupdate -i -a then run one of 2 commands depending on the results (i’ve tried using the exit code but it gives a 0 if it fails under certain conditions)

    this is what i’d scraped together but it doesn’t work and your examples look much simpler!

    if [[ $var == *”Done.” || “No new software available” || “No updates are available.”* ]]
    then
    say woop woop

    exit 0
    else

    echo “updates failed”
    say failed sad sad face
    exit 1
    fi

    Thank you
    Andy

  • Andy McPob Apr 8, 2015 @ 14:12

    missed the top of!!

    softwareupdate -i -a
    
    var=`softwareupdate -i -a`
    
    if [[ $var == *"Done." || "No new software available" || "No updates are available."* ]]
    then
      say woop woop
       
      exit 0
    else
    
      echo "updates failed"
      say failed sad sad face
      exit 1
    fi
    
  • Andy McPob Apr 8, 2015 @ 18:09

    So i’ve got this do do what i need now, could you offer a more robust and tidier method ?

    var=$(softwareupdate -i -a 2>&1)
    
    if [[ $var == *"Done."* ]] || [[ $var == *"No new software available"* ]] || [[ $var == *"No updates are available"* ]]
    then
    echo "updates complete"
      say woop hoorah woop de doop
       	exit 0
       
    else
    echo "updates failed"
      say boo 
    	exit 1
    fi
    
  • Abhishek Jun 3, 2016 @ 5:07

    Hi All,

    I was trying to get the Output of wget command in a varriable but its not storing it.

    i am using it as
    a=`wget -O ./google.jpg https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png`

    when i am doing echo $a its shows blank

    Please help me to store this in a varriable

  • Rejocktana Aug 8, 2016 @ 11:57

    Hi,

    im trying to assign Output of Shell Command To a Variable in my C-programm. I generate some CAN-Data with “cangen” but i need this data for my C-programm. I dont find a way to do that. Can somebody help me please. I use Netbeans as IDE.

    thank you

  • Emir Emiro?lu Jan 3, 2017 @ 11:33

    This tutorial is opened a new world for me. :) Fully automated nginx configurations with just a domain name input. I’ll save about 10-20 hours per month! You write the script once and use many times for different cases.
    Thanks for this amazing tutorial!

  • GreyGnome Jan 24, 2017 @ 18:11

    You can perform assignment to multiple variables by eg doing something like this:


    read nmi0 nmi1 < <(grep NMI /proc/interrupts | awk '{print $2 " " $3}')

    The redirect stdin from a shell command is quite useful, I’ve found.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.