Command substitution is nothing but run a shell command and store it's output to a variable or display back using echo command. For example, display date and time:
echo "Today is $(date)"
echo "Computer name is $(hostname)"
You can use the grave accent (`) to perform a command substitution. The syntax is:
Command substitution in an echo command
echo "Text $(command-name)"
echo -e "List of logged on users and what they are doing:\n $(w)"
List of logged on users and what they are doing: 09:49:06 up 4:09, 3 users, load average: 0.34, 0.33, 0.28 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT vivek tty7 :0 05:40 ? 9:06m 0.09s /usr/bin/gnome- vivek pts/0 :0.0 07:02 0.00s 2:07m 0.13s bash vivek pts/2 :0.0 09:03 20:46m 0.04s 0.00s /bin/bash ./ssl
Command substitution and shell variables
You can store command output to a shell variable using the following syntax:
Store current date and time to a variable called NOW:
NOW=$(date) echo $NOW
Store system's host name to a variable called SERVERNAME:
SERVERNAME=$(hostname) echo $SERVERNAME
Store current working directory name to a variable called CWD:
CWD=$(pwd) cd /path/some/where/else echo "Current dir $(pwd) and now going back to old dir .." cd $CWD
Command substitution and shell loops
Shell loop can use command substitution to get input:
for f in $(ls /etc/*.conf) do echo $f done