[Next] [Previous] [Up] [Top] [Contents]

CHAPTER 9 Shell Programming

9.5 Parameter Substitution


You can reference parameters abstractly and substitute values for them based on conditional settings using the operators defined below. Again we will use the curly braces ({}) to isolate the variable and its operators.

$parameter substitute the value of parameter for this string

${parameter} same as above. The brackets are helpful if there's no separation between this parameter and a neighboring string.

$parameter= sets parameter to null.

${parameter-default} if parameter is not set, then use default as the value here. The parameter is not reset.

${parameter=default} if parameter is not set, then set it to default and use the new value

${parameter+newval) if parameter is set, then use newval, otherwise use nothing here. The parameter is not reset.

${parameter?message} if parameter is not set, then display message. If parameter is set, then use its current value.

There are no spaces in the above operators. If a colon (:) is inserted before the -, =, +, or ? then a test if first performed to see if the parameter has a non-null setting.

The C shell has a few additional ways of substituting parameters:

$list[n] selects the nth word from list

${list[n]} same as above

$#list report the number of words in list

$?parameter return 1 if parameter is set, 0 otherwise

${?parameter} same as above

$< read a line from stdin

The C shell also defines the array, $argv[n] to contain the n arguments on the command line and $#argv to be the number of arguments, as noted in Table 9.1.

To illustrate some of these features we'll use the test script below.

#!/bin/sh

param0=$0

test -n "$1" && param1=$1

test -n "$2" && param2=$2

test -n "$3" && param3=$3

echo 0: $param0

echo "1: ${param1-1}: \c" ;echo $param1

echo "2: ${param2=2}: \c" ;echo $param2

echo "3: ${param3+3}: \c" ;echo $param3

In the script we first test to see if the variable exists, if so we set a parameter to its value. Below this we report the values, allowing substitution.

In the first run through the script we won't provide any arguments:

$ ./parameter.sh

0: ./parameter.sh # always finds $0

1: 1: # substitute 1, but don't assign this value

2: 2: 2 # substitute 2 and assign this value

3: : # don't substitute

In the second run through the script we'll provide the arguments:

$ ./parameter one two three

0: ./parameter.sh # always finds $0

1: one: one # don't substitute, it already has a value

2: two: two # don't substitute, it already has a value

3: 3: three # substitute 3, but don't assign this value


Introduction to Unix - 14 AUG 1996
[Next] [Previous] [Up] [Top] [Contents]