Bourne Shell Scripting/Substitution

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Substitution refers to the shell replacing parts of the command before the command is run. For example, the shell might change

$ ls -d arch/$LOGNAME/{i386,$(uname -m)}

into

$ ls -d arch/puffy/i386 arch/puffy/alpha

before running the command.

We can use the echo command to test substitutions. The echo command simply echoes its arguments. (Exception: if "-n" is the first argument, it is treated as an option to echo.) So, if the arguments look different, then the shell must have changed them.

$ echo -d arch/$LOGNAME/{i386,$(uname -m)}
-d arch/puffy/i386 arch/puffy/alpha

[edit] Parameter Substitution

Parameter substitution is used to read shell parameters (variables). You can also use it for environment variables, because those are just exported parameters. You can also use it for environment variables inherited by this shell from its parent process, such as login, xterm, or another shell.

$ echo $TERM
xterm
$ echo $TERM/text
xterm/text
$ echo $TERMs

$ echo ${TERM}s
xterms
$ echo ${HOME##*/}
puffy
$ echo ${HOME%/*}
/home

[edit] Command Substitution

In the Bourne-compatible shells, one can embed commands in other commands and use command substitution to replace part of a command with the result of the embedded command.

For example, uname -s gives the name of the operating system:

$ uname -s
OpenBSD

The following command substitution $(uname -s) determines the name of the operating system and uses the name as part of an echoed message about what you are running.

$ echo You are running $(uname -s).
You are running OpenBSD.

On a different system:

$ echo You are running $(uname -s).
You are running SunOS.

So the syntax for command substitution is to put the embedded command between $( and ) marks, that is between parentheses with a dollar sign in front.

[edit] Backquoting

Older copies of sh do not recognize the POSIX command substitution using $( ... ). For these shells, the backquoting using ` is available. Some users also prefer ` as it is compatible with older shells and the C shell. However, ` makes it much harder to have command substitutions inside other command substitutions.

The command uname -m gives you the type of machine that hosts the Unix-like system.

$ echo /mnt/3.7/`uname -m`
/mnt/3.7/macppc