DistributedNetworks DistributedNetworks

Embedded Commands   «Prev  Next»
Lesson 1

Introduction to Embedded Command Execution in Unix Shell

This module introduces you to the embedded command execution feature of the UNIX shells. Also called command substitution, this allows you to embed one command inside another.
It takes the output of the embedded command and uses it as part of the surrounding command. This allows you to capture command output in shell variables or create a command on the fly based on information from another command.
By the end of this module you will be able to:

  1. Explain how embedded command execution works
  2. Identify when embedded commands are most useful
  3. Correctly form an embedded command
  4. Embed a command within a for loop
  5. Embed a command within other common commands

command substitution: Var='date', Var=$(date)

Another very common way of setting a variable is to set its value to the output of a given command. This is really a variant of the fi rst format: VAR=value. If you want a variable set to "Monday" on Mondays, "Tuesday" on Tuesdays, and so on, you can use the %A fl ag to the date command, which tells date to give you the appropriate word for today, in the current locale.

command substitution is the act of inserting the output of one command as another command. There are two forms of command substitution.
  1. The standard form uses backticks around the command line to indicate command substitution;
  2. The newer form uses $(cmd).
Command substitutions can be nested; backticks have to be escaped with a backslash. The following code snippets show the two forms; the quotes around the variable are required to keep the linebreaks between the output lines. The final linebreak is always removed.

$ foo='ls -l \'which grep\' /usr/bin/test'
$ echo FOO is: "$foo"
FOO is: -rwxr-xr-x 1 root root 119288 Apr 22 2010 /bin/grep
-rwxr-xr-x 1 root root 30136 Apr 28 2010 /usr/bin/test
$ bar=$(ls -l $(which grep) /usr/bin/test)
$ echo BAR is: "$bar"
BAR is: -rwxr-xr-x 1 root root 119288 Apr 22 2010 /bin/grep
-rwxr-xr-x 1 root root 30136 Apr 28 2010 /usr/bin/test