Command Substitution
Normally, when you run a command from a script, the output from the command goes to the standard output: usually the user’s terminal. However, you may want to do further work with the output from the command, or use it to make decisions within the script.
Lets take a simple example. Suppose that you want to display the message, “Your current working directory is “ followed by the working directory. This can be done by inserting the output from the pwd command into the echo command, using a technique known as command substitution. There are two ways of doing this. The first is to enclose the name of the command in back quotes thus: `pwd`. The second is to enclose it in brackets and prefix it with the $ sign as follows: $(pwd).
So the above example could be entered into a script as follows:
echo Your current working directory is $(pwd)
This facility can be very useful in installation scripts, which may need to install different resources depending on system information such as the type of processor or operating system.
The uname command displays information about the current operating environment. Various switches can be used with it:
-a Display all information
-s Display the name of the operating system
-p Display the type of processor
-r Display the release number of the operating system.
The following is part of a script that uses the name of the operating system to decide which files to install.
ins_opsys=$(uname –s)
if [ $ins_opsys = SunOS ]
then
tar xvf sunfiles.tar
elif [ $ins_opsys = UnixWare ]
then
tar xvf unixwarefiles.tar
elif [ $ins_opsys = AIX ]
then
tar xvf aixfiles.tar
else
echo Operating system $ins_opsys not yet supported
fi
Command substitution becomes even more useful when combined with techniques covered in the next few articles. We will learn how to split the output from the command so that we can use selected parts of it, or reformat it. We will also learn how to deal with multi-line output.