36.7. Parameter SubstitutionThe Bourne shell has a handy set of operators for testing and setting shell variables. They're listed in Table 36-1. Table 36-1. Bourne shell parameter substitution operators
If you omit the colon (:) from the expressions in Table 36-1, the shell doesn't check for an empty parameter. In other words, the substitution happens whenever the parameter is set. (That's how some early Bourne shells work: they don't understand a colon in parameter substitution.) To see how parameter substitution works, here's another version of the bkedit script (Section 35.13, Section 35.16): +#!/bin/sh if cp "$1" "$1.bak" then ${VISUAL:-/usr/ucb/vi} "$1" exit # Use status from editor else echo "`basename $0` quitting: can't make backup?" 1>&2 exit 1 fi If the VISUAL (Section 35.5) environment variable is set and is not empty, its value (such as /usr/local/bin/emacs) is used and the command line becomes /usr/local/bin/emacs "$1". If VISUAL isn't set, the command line defaults to /usr/ucb/vi "$1". You can use parameter substitution operators in any command line. You'll see them used with the colon (:) operator (Section 36.6), checking or setting default values. There's an example below. The first substitution (${nothing=default}) leaves $nothing empty because the variable has been set. The second substitution sets $nothing to default because the variable has been set but is empty. The third substitution leaves $something set to stuff: +nothing= something=stuff : ${nothing=default} : ${nothing:=default} : ${something:=default} Several Bourne-type shells have similar string editing operators, such as ${var##pattern}. They're useful in shell programs, as well as on the command line and in shell setup files. See your shell's manual page for more details. -- JP Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|