Wednesday, January 9, 2013

Shell Programming:COMMAND SUBSTITUTION


COMMAND SUBSTITUTION:

* The next step is to consider shell command substitution. Like any programming language, the shell does exactly what it is told to do, and so it is important to be very specific when telling it to do something. As an example, consider the "fgrep" command, which searches a file for a string. For example, to search a file named "source.txt" for the string "Coyote", enter:
   fgrep Coyote source.txt
-- and it would print out the matching lines. However, suppose we wanted to search for "Wile E. Coyote". If we did this as:
   fgrep Wile E. Coyote source.txt
-- we'd get an error message that "fgrep" couldn't open "E.". The string has to be enclosed in double-quotes (""):
   fgrep "Wile E. Coyote" source.txt
If a string has a special character in it, such as "*" or "?", that must be interpreted as a "literal" and not a wildcard, the shell can get a little confused. To ensure that the wildcards are not interpreted, the wildcard can either be "escaped" with a backslash ("\*" or "\?") or the string can be enclosed in single quotes, which prevents the shell from interpreting any of the characters within the string. For example, if:
   echo "$shvar"
-- is executed from a shell program, it would output the value of the shell variable "$shvar". In contrast, executing:
   echo '$shvar'
-- the output is the string "$shvar".
* Having considered "double-quoting" and "single-quoting", let's now consider "back-quoting". This is a little tricky to explain. As a useful tool, consider the "expr" command, which can be used to perform simple math from the command line:
   expr 2 + 4
This displays the value "6". There must be spaces between the parameters; in addition, to perform a multiplication the "*" has to be "escaped" so the shell doesn't interpret it:
   expr 3 \* 7 
Now suppose the string "expr 12 / 3" has been stored in a shell variable named "shcmd"; then executing:
   echo $shcmd
-- or:
   echo "$shcmd"
-- would simply produce the text "expr 12 / 3". If single-quotes were used:
   echo '$shcmd'
-- the result would be the string "$shcmd". However, if back-quotes, the reverse form of a single quote, were used:
   echo `$shcmd`
-- the result would be the value "4", since the string inside "shcmd" is executed. This is an extremely powerful technique that can be very confusing to use in practice.

0 comments:

Post a Comment

Powered by Blogger.