Command Substitution

Team-Fly    

Solaris™ Operating Environment Boot Camp
By David Rhodes, Dominic Butler
Table of Contents
Chapter 5.  Shells


We have looked at the use of the single quote (') and the use of the double quote ("), but the back quote (`) is also a shell metacharacter and it is used to enable command substitution.

If the shell sees a pair of back quotes in a command line it will execute the entire command contained inside the back quotes first and then replace it with the output from that command. Then it will run the original command.

So if we wanted to edit a script called script1.sh that existed in a directory included in our path we could use the which command (we've already described this earlier) to locate the script and then type in the full path name:

 $ which script1.sh /usr/local/bin/script1.sh $ vi /usr/local/bin/script1.sh <output removed for clarity> $ 

Alternatively we could make use of command substitution to do the whole thing in one command:

 $ vi `which script1.sh` <output removed for clarity> $ 

The shell will first run the command enclosed in the back quotes and then replace the back quotes and their contents with the output from that command, which then becomes the parameter to the vi command.

The back quote is actually a construct from the Bourne Shell, but it also works with the Korn Shell as the Korn Shell is fully compatible with the Bourne Shell. In the future this compatibility cannot be guaranteed so it is better to use the actual Korn Shell syntax, which is to use "$(" in place of the opening back quote and ")" in place of the closing back quote. So the above example would be written as follows:

 $ vi $(which script1.sh) <output removed for clarity> $ 

    Team-Fly    
    Top
     



    Solaris Operating Environment Boot Camp
    Solaris Operating Environment Boot Camp
    ISBN: 0130342874
    EAN: 2147483647
    Year: 2002
    Pages: 301

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net