Skip to main content

Command substitution means nothing more but to run a shell command and store its output to a variable or display back using echo command. For example, display date and time.

## Syntax
`command-name`
$(command-name)

# Examples
echo "Today is $(date)"
echo "Computer name is $(hostname)"
echo -e "List of logged on users and what they are doing:\n $(w)"

## Command substitution and shell variables
NOW=$(date)
echo "$NOW"

# Store system's host name to a variable called SERVERNAME
SERVERNAME=$(hostname)
echo "Running command @ $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

# Shell loop can use command substitution to get input
for f in $(ls /etc/*.conf)
do
   echo "$f"
done

# However, a recommend syntax is as follows for file selections
for f in /etc/*.conf
do
   echo "$f"
done