home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 45.11 The Multipurpose jot Command Chapter 45
Shell Programming for the Initiated
Next: 45.13 Save Disk Space and Programming: Multiple Names for a Program
 

45.12 Parameter Substitution

The Bourne shell has a handy set of operators for testing and setting shell variables. They're listed in

Table 45.2: Bourne Shell Parameter Substitution Operators
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 45-2, the shell doesn't check for an empty parameter. In other words, the substitution will happen 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 ( 44.8 , 44.11 ) :

#!/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 ( 6.3 ) environment variable is set and is not empty, its value (like /usr/local/bin/emacs ) is used and the command line becomes /usr/local/bin/emacs "$1" . If VISUAL isn't set, the command line will default to /usr/ucb/vi "$1" .

You can use parameter substitution operators in any command line. You'll see them used with the colon ( : ) operator ( 45.9 ) , checking or setting default values. There's an example below. The first substitution ( ${nothing=default} ) will leave $nothing empty because the variable has been set. The second substitution will set $nothing to default because the variable has been set but is empty. The third substitution will leave $something set to stuff :

nothing=
something=stuff
: ${nothing=default}
: ${nothing:=default}
: ${something:=default}

The Korn shell and bash have similar string editing operators ( 9.7 ) like ${ var ## pattern } . They're useful in shell programs, as well as on the command line and in shell setup files.

- JP


Previous: 45.11 The Multipurpose jot Command UNIX Power Tools Next: 45.13 Save Disk Space and Programming: Multiple Names for a Program
45.11 The Multipurpose jot Command Book Index 45.13 Save Disk Space and Programming: Multiple Names for a Program

The UNIX CD Bookshelf Navigation The UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System