Introducing UNIX and Linux |
Introduction to shellsOverview |
Parameter expansionWe have already considered assigning values to variables in the previous chapter. In this section, we look at the shell's features that allow it to examine in detail whether variables have been set values and what form those values take. Often you will write scripts where you will use variables that
you assume will have certain values. They may be variables you have
created yourself for your own benefit, or they may be 'system'
variables, such as It is thus good practice whenever writing a script that relies on a variable not defined as necessarily existing in POSIX, to check that it has in fact been assigned a value, and that that value is of the correct format. Parameter expansion is the mechanism usually employed. Consider if [ -z "$NAME" ] then NAME="A.N. Other" fi This will work. It is also verbose - a script that uses many
variables would be tedious to write if you include checks for all
the variables in the script. It should be emphasised that it is a
very good idea to check that variables have in fact been assigned
values before you attempt to use those variables. Parameter
expansion will not do anything that cannot already be done using
At this point we need to discuss an apparently minor - but
nonetheless important - feature of variables. If a variable has not
got a value, this can be for two reasons. Either it has not been
mentioned at all before, in which case it is
unset, or it has been set but has the null string
(a null string
or, alternatively, since it would not be ambiguous:
For most purposes the two situations have the same result. If
you wish to unset a variable rather than just set its value to
null, use
To ensure that a variable is set, the form is
which expands to the value of variable, if that
variable has been set or is null, otherwise to default.
For instance, instead of the
The following script will check to see if variable
Try this, first of all without
Worked exampleCreate a welcome message to initially check variable
If a variable is unset, the
Another behaviour that might be desirable is for the shell to
give you an error message if a variable is unset - this is
especially useful if there is no sensible default value you can
substitute for the variable. Replace
If you follow the
Worked exampleEnsure that
When using
We can discover the length (i.e. the numbers of characters) of a string:
Note that Worked exampleUse a loop to print out a line of 50 plusses so: LINE="" # Set LINE to null until [ ${#LINE} -eq 50 ] # Until its length is 50 ... do LINE=$LINE+ # add another "+" to it ... done echo $LINE # and finally display the line |
Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck