4.4. Special Variable Types

Local variables

Variables visible only within a code block or function (see also local variables in functions)

Environmental variables

Variables that affect the behavior of the shell and user interface

Note

In a more general context, each process has an "environment", that is, a group of variables that the process may reference. In this sense, the shell behaves like any other process.

Every time a shell starts, it creates shell variables that correspond to its own environmental variables. Updating or adding new environmental variables causes the shell to update its environment, and all the shell's child processes (the commands it executes) inherit this environment.

Caution

The space allotted to the environment is limited. Creating too many environmental variables or ones that use up excessive space may cause problems.

 bash$ eval "`seq 10000 | sed -e 's/.*/export var&=ZZZZZZZZZZZZZZ/'`"
 
 bash$ du
 bash: /usr/bin/du: Argument list too long
 	          

Note: this "error" has been fixed, as of kernel version 2.6.23.

(Thank you, Stéphane Chazelas for the clarification, and for providing the above example.)

If a script sets environmental variables, they need to be "exported," that is, reported to the environment local to the script. This is the function of the export command.

Note

A script can export variables only to child processes, that is, only to commands or processes which that particular script initiates. A script invoked from the command-line cannot export variables back to the command-line environment. Child processes cannot export variables back to the parent processes that spawned them.

Definition: A child process is a subprocess launched by another process, its parent.

Positional parameters

Arguments passed to the script from the command line [1] : $0, $1, $2, $3 . . .

$0 is the name of the script itself, $1 is the first argument, $2 the second, $3 the third, and so forth. [2] After $9, the arguments must be enclosed in brackets, for example, ${10}, ${11}, ${12}.

The special variables $* and $@ denote all the positional parameters.


Example 4-5. Positional Parameters

   1 #!/bin/bash
   2 
   3 # Call this script with at least 10 parameters, for example
   4 # ./scriptname 1 2 3 4 5 6 7 8 9 10
   5 MINPARAMS=10
   6 
   7 echo
   8 
   9 echo "The name of this script is \"$0\"."
  10 # Adds ./ for current directory
  11 echo "The name of this script is \"`basename $0`\"."
  12 # Strips out path name info (see 'basename')
  13 
  14 echo
  15 
  16 if [ -n "$1" ]              # Tested variable is quoted.
  17 then
  18  echo "Parameter #1 is $1"  # Need quotes to escape #
  19 fi 
  20 
  21 if [ -n "$2" ]
  22 then
  23  echo "Parameter #2 is $2"
  24 fi 
  25 
  26 if [ -n "$3" ]
  27 then
  28  echo "Parameter #3 is $3"
  29 fi 
  30 
  31 # ...
  32 
  33 
  34 if [ -n "${10}" ]  # Parameters > $9 must be enclosed in {brackets}.
  35 then
  36  echo "Parameter #10 is ${10}"
  37 fi 
  38 
  39 echo "-----------------------------------"
  40 echo "All the command-line parameters are: "$*""
  41 
  42 if [ $# -lt "$MINPARAMS" ]
  43 then
  44   echo
  45   echo "This script needs at least $MINPARAMS command-line arguments!"
  46 fi  
  47 
  48 echo
  49 
  50 exit 0

Bracket notation for positional parameters leads to a fairly simple way of referencing the last argument passed to a script on the command-line. This also requires indirect referencing.

   1 args=$#           # Number of args passed.
   2 lastarg=${!args}
   3 # Note: This is an *indirect reference* to $args ...
   4 
   5 
   6 # Or:       lastarg=${!#}             (Thanks, Chris Monson.)
   7 # This is an *indirect reference* to the $# variable.
   8 # Note that lastarg=${!$#} doesn't work.

Some scripts can perform different operations, depending on which name they are invoked with. For this to work, the script needs to check $0, the name it was invoked by. [3] There must also exist symbolic links to all the alternate names of the script. See Example 16-2.

Tip

If a script expects a command-line parameter but is invoked without one, this may cause a null variable assignment, generally an undesirable result. One way to prevent this is to append an extra character to both sides of the assignment statement using the expected positional parameter.

   1 variable1_=$1_  # Rather than variable1=$1
   2 # This will prevent an error, even if positional parameter is absent.
   3 
   4 critical_argument01=$variable1_
   5 
   6 # The extra character can be stripped off later, like so.
   7 variable1=${variable1_/_/}
   8 # Side effects only if $variable1_ begins with an underscore.
   9 # This uses one of the parameter substitution templates discussed later.
  10 # (Leaving out the replacement pattern results in a deletion.)
  11 
  12 #  A more straightforward way of dealing with this is
  13 #+ to simply test whether expected positional parameters have been passed.
  14 if [ -z $1 ]
  15 then
  16   exit $E_MISSING_POS_PARAM
  17 fi
  18 
  19 
  20 #  However, as Fabian Kreutz points out,
  21 #+ the above method may have unexpected side-effects.
  22 #  A better method is parameter substitution:
  23 #         ${1:-$DefaultVal}
  24 #  See the "Parameter Substition" section
  25 #+ in the "Variables Revisited" chapter.

---


Example 4-6. wh, whois domain name lookup

   1 #!/bin/bash
   2 # ex18.sh
   3 
   4 # Does a 'whois domain-name' lookup on any of 3 alternate servers:
   5 #                    ripe.net, cw.net, radb.net
   6 
   7 # Place this script -- renamed 'wh' -- in /usr/local/bin
   8 
   9 # Requires symbolic links:
  10 # ln -s /usr/local/bin/wh /usr/local/bin/wh-ripe
  11 # ln -s /usr/local/bin/wh /usr/local/bin/wh-apnic
  12 # ln -s /usr/local/bin/wh /usr/local/bin/wh-tucows
  13 
  14 E_NOARGS=75
  15 
  16 
  17 if [ -z "$1" ]
  18 then
  19   echo "Usage: `basename $0` [domain-name]"
  20   exit $E_NOARGS
  21 fi
  22 
  23 # Check script name and call proper server.
  24 case `basename $0` in    # Or:    case ${0##*/} in
  25     "wh"       ) whois $1@whois.tucows.com;;
  26     "wh-ripe"  ) whois $1@whois.ripe.net;;
  27     "wh-apnic" ) whois $1@whois.apnic.net;;
  28     "wh-cw"    ) whois $1@whois.cw.net;;
  29     *          ) echo "Usage: `basename $0` [domain-name]";;
  30 esac 
  31 
  32 exit $?

---

The shift command reassigns the positional parameters, in effect shifting them to the left one notch.

$1 <--- $2, $2 <--- $3, $3 <--- $4, etc.

The old $1 disappears, but $0 (the script name) does not change. If you use a large number of positional parameters to a script, shift lets you access those past 10, although {bracket} notation also permits this.


Example 4-7. Using shift

   1 #!/bin/bash
   2 # shft.sh: Using 'shift' to step through all the positional parameters.
   3 
   4 #  Name this script something like shft.sh,
   5 #+ and invoke it with some parameters.
   6 #+ For example:
   7 #             sh shft.sh a b c def 83 barndoor
   8 
   9 until [ -z "$1" ]  # Until all parameters used up . . .
  10 do
  11   echo -n "$1 "
  12   shift
  13 done
  14 
  15 echo               # Extra linefeed.
  16 
  17 # But, what happens to the "used-up" parameters?
  18 echo "$2"
  19 #  Nothing echoes!
  20 #  When $2 shifts into $1 (and there is no $3 to shift into $2)
  21 #+ then $2 remains empty.
  22 #  So, it is not a parameter *copy*, but a *move*.
  23 
  24 exit
  25 
  26 #  See also the echo-params.sh script for a "shiftless"
  27 #+ alternative method of stepping through the positional params.

The shift command can take a numerical parameter indicating how many positions to shift.

   1 #!/bin/bash
   2 # shift-past.sh
   3 
   4 shift 3    # Shift 3 positions.
   5 #  n=3; shift $n
   6 #  Has the same effect.
   7 
   8 echo "$1"
   9 
  10 exit 0
  11 
  12 # ======================== #
  13 
  14 
  15 $ sh shift-past.sh 1 2 3 4 5
  16 4
  17 
  18 #  However, as Eleni Fragkiadaki, points out,
  19 #+ attempting a 'shift' past the number of
  20 #+ positional parameters ($#) returns an exit status of 1,
  21 #+ and the positional parameters themselves do not change.
  22 #  This means possibly getting stuck in an endless loop. . . .
  23 #  For example:
  24 #      until [ -z "$1" ]
  25 #      do
  26 #         echo -n "$1 "
  27 #         shift 20    #  If less than 20 pos params,
  28 #      done           #+ then loop never ends!
  29 #
  30 # When in doubt, add a sanity check. . . .
  31 #           shift 20 || break
  32 #                    ^^^^^^^^

Note

The shift command works in a similar fashion on parameters passed to a function. See Example 36-18.

Notes

[1]

Note that functions also take positional parameters.

[2]

The process calling the script sets the $0 parameter. By convention, this parameter is the name of the script. See the manpage (manual page) for execv.

From the command-line, however, $0 is the name of the shell.
 bash$ echo $0
 bash
 
 tcsh% echo $0
 tcsh

[3]

If the the script is sourced or symlinked, then this will not work. It is safer to check $BASH_Source.