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?
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:
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 no spaces after the equals sign and command must be on right side of =. See how to assign values to shell variables for more information.
Example
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
See also:
- Command substitution - from the Linux shell scripting tutorial wiki.
You should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop













{ 3 comments… read them below or add one }
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
Error: printf “%s\n” now
Should be: printf “%s\n” “$now”
Thanks for the heads up!