Command Substitution in a Bash Shell Script

by mike on February 3, 2011

Command Substitution
Command substitution is when you take the output of one command and use it as the argument for another command.   If you simply invoke the date utility, you’ll get the following output.

date
Fri Jan 19 17:13:29 EST 2007

That works here, but it might not work well in other cases, like when you’re writing a bash script.  You would then need to consider using command substitution.  There are two ways to do this.

The first way is the more modern way, and is really the only way that you want to use.  You surround the command that you want to substitute with parentheses, and then precede it with a dollar-sign.  Here, we’re using echo to show the output of date.

echo $(date)
Fri Jan 19 17:12:57 EST 2007

You can also export the value of date to an environment variable.

export DATETIME=$(date)
echo $DATETIME
Fri Jan 19 17:12:45 EST 2007

The second method of command substitution is the older of the two methods.  It can be more complicated to use, mainly because you have to be careful to place backslashes in front of any characters that would have a special meaning to bash.  You also can’t perform nesting with it.  Although you’ll want to avoid it for your own use, you’ll still need to be aware of it for certification exam purposes.

Instead of using the $(command) structure, you’ll surround the command that you want to substitute with back-quotes.  (That’s the key next to the “1″ key.  It’s on the same key with the tilde.)  So, if you want to use this method with our previous date example, you would enter:

echo `date`
Fri Jan 19 17:54:30 EST 2007

Back tics are used with external commands to execute a command separately from the script and then be used by the script.  In this example the text string inside back tics is executed to create the variable.  This script lists the name of the individual that is logged in.

sysname.sh
#!/bin/sh
SYSNAME=`egrep “^${USER}:” /etc/passwd | cut -d: -f5`
echo $SYSNAME

The system name for the user is grabbed by looking at the start of the line “^” for in /etc/passwd and then cut is used to cut out the fifth field.  Echo is used to express the system name which has become a variable, $SYSNAME.

Command substitution is used often in scripts, so it is a tool you surely want to develop correctly.

Comments on this entry are closed.

Previous post:

Next post: