The Bourne shell has a handy set of operators for testing and setting shell variables. They're listed in Table 36-1.
Operator |
Explanation |
---|---|
${var:-default} |
If var is not set or is empty, use default instead. |
${var:=default} |
If var is not set or is empty, set it to default and use that value. |
${var:+instead} |
If var is set and is not empty, use instead. Otherwise, use nothing (null string). |
${var:?message} |
If var is set and is not empty, use its value. Otherwise, print message, if any, and exit from the shell. If message is missing, print a default message (which depends on your shell). |
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.