Used properly, variables can add power and flexibility to scripts. This requires learning their subtleties and nuances.
variables affecting bash script behavior
the path to the Bash binary itself, usually /bin/bash
an environmental variable pointing to a Bash startup file to be read when a script is invoked
a 6-element array containing version information about the installed release of Bash. This is similar to $BASH_VERSION, below, but a bit more detailed.
1 # Bash version info: 2 3 for n in 0 1 2 3 4 5 4 do 5 echo "BASH_VERSINFO[$n] = ${BASH_VERSINFO[$n]}" 6 done 7 8 # BASH_VERSINFO[0] = 2 # Major version no. 9 # BASH_VERSINFO[1] = 04 # Minor version no. 10 # BASH_VERSINFO[2] = 21 # Patch level. 11 # BASH_VERSINFO[3] = 1 # Build version. 12 # BASH_VERSINFO[4] = release # Release status. 13 # BASH_VERSINFO[5] = i386-redhat-linux-gnu # Architecture 14 # (same as $MACHTYPE). |
the version of Bash installed on the system
bash$ echo $BASH_VERSION 2.04.12(1)-release |
tcsh% echo $BASH_VERSION BASH_VERSION: Undefined variable. |
Checking $BASH_VERSION is a good method of determining which shell is running. $SHELL does not necessarily give the correct answer.
contents of the directory stack (affected by pushd and popd)
This builtin variable is the counterpart to the dirs command.
the default editor invoked by a script, usually vi or emacs.
"effective" user id number
Identification number of whatever identity the current user has assumed, perhaps by means of su.
The $EUID is not necessarily the same as the $UID. |
name of the current function
1 xyz23 () 2 { 3 echo "$FUNCNAME now executing." # xyz23 now executing. 4 } 5 6 xyz23 7 8 echo "FUNCNAME = $FUNCNAME" # FUNCNAME = 9 # Null value outside a function. |
A list of filename patterns to be excluded from matching in globbing.
groups current user belongs to
This is a listing (array) of the group id numbers for current user, as recorded in /etc/passwd.
home directory of the user, usually /home/username (see Example 9-9)
The hostname command assigns the system name at bootup in an init script. However, the gethostname() function sets the Bash internal variable $HOSTNAME. See also Example 9-9.
host type
Like $MACHTYPE, identifies the system hardware.
bash$ echo $HOSTTYPE i686 |
input field separator
This defaults to whitespace (space, tab, and newline), but may be changed, for example, to parse a comma-separated data file. Note that $* uses the first character held in $IFS. See Example 6-1.
bash$ echo $IFS | cat -vte $ bash$ bash -c 'set w x y z; IFS=":-;"; echo "$*"' w:x:y:z |
(Thanks, S. C., for clarification and examples.)
ignore EOF: how many end-of-files (control-D) the shell will ignore before logging out.
Often set in the .bashrc or /etc/profile files, this variable controls collation order in filename expansion and pattern matching. If mishandled, LC_COLLATE can cause unexpected results in filename globbing.
As of version 2.05 of Bash, filename globbing no longer distinguishes between lowercase and uppercase letters in a character range between brackets. For example, ls [A-M]* would match both File1.txt and file1.txt. To revert to the customary behavior of bracket matching, set LC_COLLATE to C by an export LC_COLLATE=C in /etc/profile and/or ~/.bashrc. |
This internal variable controls character interpretation in globbing and pattern matching.
This variable is the line number of the shell script in which this variable appears. It has significance only within the script in which it appears, and is chiefly useful for debugging purposes.
1 last_cmd_arg=$_ # Save it. 2 3 echo "At line number $LINENO, variable \"v1\" = $v1" 4 echo "Last command argument processed = $last_cmd_arg" |
machine type
Identifies the system hardware.
bash$ echo $MACHTYPE i686-debian-linux-gnu |
old working directory ("OLD-print-working-directory", previous directory you were in)
operating system type
bash$ echo $OSTYPE linux-gnu |
path to binaries, usually /usr/bin/, /usr/X11R6/bin/, /usr/local/bin, etc.
When given a command, the shell automatically does a hash table search on the directories listed in the path for the executable. The path is stored in the environmental variable, $PATH, a list of directories, separated by colons. Normally, the system stores the $PATH definition in /etc/profile and/or ~/.bashrc (see Chapter 27).
bash$ echo $PATH /bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin:/sbin:/usr/sbin |
PATH=${PATH}:/opt/bin appends the /opt/bin directory to the current path. In a script, it may be expedient to temporarily add a directory to the path in this way. When the script exits, this restores the original $PATH (a child process, such as a script, may not change the environment of the parent process, the shell).
The current "working directory", ./, is usually omitted from the $PATH as a security measure. |
Exit status of last executed pipe. Interestingly enough, this does not give the same result as the exit status of the last executed command.
bash$ echo $PIPESTATUS 0 bash$ ls -al | bogus_command bash: bogus_command: command not found bash$ echo $PIPESTATUS 141 bash$ ls -al | bogus_command bash: bogus_command: command not found bash$ echo $? 127 |
The $PPID of a process is the process id (pid) of its parent process. [1]
Compare this with the pidof command.
This is the main prompt, seen at the command line.
The secondary prompt, seen when additional input is expected. It displays as ">".
The tertiary prompt, displayed in a select loop (see Example 10-27).
The quartenary prompt, shown at the beginning of each line of output when invoking a script with the -x option. It displays as "+".
working directory (directory you are in at the time)
This is the analog to the pwd builtin command.
1 #!/bin/bash 2 3 E_WRONG_DIRECTORY=73 4 5 clear # Clear screen. 6 7 TargetDirectory=/home/bozo/projects/GreatAmericanNovel 8 9 cd $TargetDirectory 10 echo "Deleting stale files in $TargetDirectory." 11 12 if [ "$PWD" != "$TargetDirectory" ] 13 then # Keep from wiping out wrong directory by accident. 14 echo "Wrong directory!" 15 echo "In $PWD, rather than $TargetDirectory!" 16 echo "Bailing out!" 17 exit $E_WRONG_DIRECTORY 18 fi 19 20 rm -rf * 21 rm .[A-Za-z0-9]* # Delete dotfiles. 22 # rm -f .[^.]* ..?* to remove filenames beginning with multiple dots. 23 # (shopt -s dotglob; rm -f *) will also work. 24 # Thanks, S.C. for pointing this out. 25 26 # Filenames may contain all characters in the 0 - 255 range, except "/". 27 # Deleting files beginning with weird characters is left as an exercise. 28 29 # Various other operations here, as necessary. 30 31 echo 32 echo "Done." 33 echo "Old files deleted in $TargetDirectory." 34 echo 35 36 37 exit 0 |
The default value when a variable is not supplied to read. Also applicable to select menus, but only supplies the item number of the variable chosen, not the value of the variable itself.
1 #!/bin/bash 2 3 echo 4 echo -n "What is your favorite vegetable? " 5 read 6 7 echo "Your favorite vegetable is $REPLY." 8 # REPLY holds the value of last "read" if and only if 9 # no variable supplied. 10 11 echo 12 echo -n "What is your favorite fruit? " 13 read fruit 14 echo "Your favorite fruit is $fruit." 15 echo "but..." 16 echo "Value of \$REPLY is still $REPLY." 17 # $REPLY is still set to its previous value because 18 # the variable $fruit absorbed the new "read" value. 19 20 echo 21 22 exit 0 |
The number of seconds the script has been running.
1 #!/bin/bash 2 3 ENDLESS_LOOP=1 4 INTERVAL=1 5 6 echo 7 echo "Hit Control-C to exit this script." 8 echo 9 10 while [ $ENDLESS_LOOP ] 11 do 12 if [ "$SECONDS" -eq 1 ] 13 then 14 units=second 15 else 16 units=seconds 17 fi 18 19 echo "This script has been running $SECONDS $units." 20 sleep $INTERVAL 21 done 22 23 24 exit 0 |
the list of enabled shell options, a readonly variable
Shell level, how deeply Bash is nested. If, at the command line, $SHLVL is 1, then in a script it will increment to 2.
If the $TMOUT environmental variable is set to a non-zero value time, then the shell prompt will time out after time seconds. This will cause a logout.
Unfortunately, this works only while waiting for input at the shell prompt console or in an xterm. While it would be nice to speculate on the uses of this internal variable for timed input, for example in combination with read, $TMOUT does not work in that context and is virtually useless for shell scripting. (Reportedly the ksh version of a timed read does work). |
Implementing timed input in a script is certainly possible, but hardly seems worth the effort. One method is to set up a timing loop to signal the script when it times out. This also requires a signal handling routine to trap (see Example 30-4) the interrupt generated by the timing loop (whew!).
Example 9-2. Timed Input
1 #!/bin/bash 2 # timed-input.sh 3 4 # TMOUT=3 useless in a script 5 6 TIMELIMIT=3 # Three seconds in this instance, may be set to different value. 7 8 PrintAnswer() 9 { 10 if [ "$answer" = TIMEOUT ] 11 then 12 echo $answer 13 else # Don't want to mix up the two instances. 14 echo "Your favorite veggie is $answer" 15 kill $! # Kills no longer needed TimerOn function running in background. 16 # $! is PID of last job running in background. 17 fi 18 19 } 20 21 22 23 TimerOn() 24 { 25 sleep $TIMELIMIT && kill -s 14 $$ & 26 # Waits 3 seconds, then sends sigalarm to script. 27 } 28 29 Int14Vector() 30 { 31 answer="TIMEOUT" 32 PrintAnswer 33 exit 14 34 } 35 36 trap Int14Vector 14 # Timer interrupt (14) subverted for our purposes. 37 38 echo "What is your favorite vegetable " 39 TimerOn 40 read answer 41 PrintAnswer 42 43 44 # Admittedly, this is a kludgy implementation of timed input, 45 # but pretty much as good as can be done with Bash. 46 # (Challenge to reader: come up with something better.) 47 48 # If you need something a bit more elegant... 49 # consider writing the application in C or C++, 50 # using appropriate library functions, such as 'alarm' and 'setitimer'. 51 52 exit 0 |
An alternative is using stty.
Example 9-3. Once more, timed input
1 #!/bin/bash 2 # timeout.sh 3 4 # Written by Stephane Chazelas, 5 # and modified by the document author. 6 7 INTERVAL=5 # timeout interval 8 9 timedout_read() { 10 timeout=$1 11 varname=$2 12 old_tty_settings=`stty -g` 13 stty -icanon min 0 time ${timeout}0 14 eval read $varname # or just read $varname 15 stty "$old_tty_settings" 16 # See man page for "stty". 17 } 18 19 echo; echo -n "What's your name? Quick! " 20 timedout_read $INTERVAL your_name 21 22 # This may not work on every terminal type. 23 # The maximum timeout depends on the terminal. 24 # (it is often 25.5 seconds). 25 26 echo 27 28 if [ ! -z "$your_name" ] # If name input before timeout... 29 then 30 echo "Your name is $your_name." 31 else 32 echo "Timed out." 33 fi 34 35 echo 36 37 # The behavior of this script differs somewhat from "timed-input.sh". 38 # At each keystroke, the counter resets. 39 40 exit 0 |
user id number
current user's user identification number, as recorded in /etc/passwd
This is the current user's real id, even if she has temporarily assumed another identity through su. $UID is a readonly variable, not subject to change from the command line or within a script, and is the counterpart to the id builtin.
Example 9-4. Am I root?
1 #!/bin/bash 2 # am-i-root.sh: Am I root or not? 3 4 ROOT_UID=0 # Root has $UID 0. 5 6 if [ "$UID" -eq "$ROOT_UID" ] # Will the real "root" please stand up? 7 then 8 echo "You are root." 9 else 10 echo "You are just an ordinary user (but mom loves you just the same)." 11 fi 12 13 exit 0 14 15 16 # ============================================================= # 17 # Code below will not execute, because the script already exited. 18 19 # An alternate method of getting to the root of matters: 20 21 ROOTUSER_NAME=root 22 23 username=`id -nu` 24 if [ "$username" = "$ROOTUSER_NAME" ] 25 then 26 echo "Rooty, toot, toot. You are root." 27 else 28 echo "You are just a regular fella." 29 fi 30 31 exit 0 |
See also Example 2-2.
The variables $ENV, $LOGNAME, $MAIL, $TERM, $USER, and $USERNAME are not Bash builtins. These are, however, often set as environmental variables in one of the Bash startup files. $SHELL, the name of the user's login shell, may be set from /etc/passwd or in an "init" script, and it is likewise not a Bash builtin.
|
Positional Parameters
positional parameters, passed from command line to script, passed to a function, or set to a variable (see Example 5-5 and Example 11-10)
number of command line arguments [2] or positional parameters (see Example 34-2)
All of the positional parameters, seen as a single word
Same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.
Example 9-5. arglist: Listing arguments with $* and $@
1 #!/bin/bash 2 # Invoke this script with several arguments, such as "one two three". 3 4 E_BADARGS=65 5 6 if [ ! -n "$1" ] 7 then 8 echo "Usage: `basename $0` argument1 argument2 etc." 9 exit $E_BADARGS 10 fi 11 12 echo 13 14 index=1 15 16 echo "Listing args with \"\$*\":" 17 for arg in "$*" # Doesn't work properly if "$*" isn't quoted. 18 do 19 echo "Arg #$index = $arg" 20 let "index+=1" 21 done # $* sees all arguments as single word. 22 echo "Entire arg list seen as single word." 23 24 echo 25 26 index=1 27 28 echo "Listing args with \"\$@\":" 29 for arg in "$@" 30 do 31 echo "Arg #$index = $arg" 32 let "index+=1" 33 done # $@ sees arguments as separate words. 34 echo "Arg list seen as separate words." 35 36 echo 37 38 exit 0 |
The $@ special parameter finds use as a tool for filtering input into shell scripts. The cat "$@" construction accepts input to a script either from stdin or from files given as parameters to the script. See Example 12-16 and Example 12-17.
The $* and $@ parameters sometimes display inconsistent and puzzling behavior, depending on the setting of $IFS. |
Example 9-6. Inconsistent $* and $@ behavior
1 #!/bin/bash 2 3 # Erratic behavior of the "$*" and "$@" internal Bash variables, 4 # depending on whether these are quoted or not. 5 # Word splitting and linefeeds handled inconsistently. 6 7 # This example script by Stephane Chazelas, 8 # and slightly modified by the document author. 9 10 11 set -- "First one" "second" "third:one" "" "Fifth: :one" 12 # Setting the script arguments, $1, $2, etc. 13 14 echo 15 16 echo 'IFS unchanged, using "$*"' 17 c=0 18 for i in "$*" # quoted 19 do echo "$((c+=1)): [$i]" # This line remains the same in every instance. 20 # Echo args. 21 done 22 echo --- 23 24 echo 'IFS unchanged, using $*' 25 c=0 26 for i in $* # unquoted 27 do echo "$((c+=1)): [$i]" 28 done 29 echo --- 30 31 echo 'IFS unchanged, using "$@"' 32 c=0 33 for i in "$@" 34 do echo "$((c+=1)): [$i]" 35 done 36 echo --- 37 38 echo 'IFS unchanged, using $@' 39 c=0 40 for i in $@ 41 do echo "$((c+=1)): [$i]" 42 done 43 echo --- 44 45 IFS=: 46 echo 'IFS=":", using "$*"' 47 c=0 48 for i in "$*" 49 do echo "$((c+=1)): [$i]" 50 done 51 echo --- 52 53 echo 'IFS=":", using $*' 54 c=0 55 for i in $* 56 do echo "$((c+=1)): [$i]" 57 done 58 echo --- 59 60 var=$* 61 echo 'IFS=":", using "$var" (var=$*)' 62 c=0 63 for i in "$var" 64 do echo "$((c+=1)): [$i]" 65 done 66 echo --- 67 68 echo 'IFS=":", using $var (var=$*)' 69 c=0 70 for i in $var 71 do echo "$((c+=1)): [$i]" 72 done 73 echo --- 74 75 var="$*" 76 echo 'IFS=":", using $var (var="$*")' 77 c=0 78 for i in $var 79 do echo "$((c+=1)): [$i]" 80 done 81 echo --- 82 83 echo 'IFS=":", using "$var" (var="$*")' 84 c=0 85 for i in "$var" 86 do echo "$((c+=1)): [$i]" 87 done 88 echo --- 89 90 echo 'IFS=":", using "$@"' 91 c=0 92 for i in "$@" 93 do echo "$((c+=1)): [$i]" 94 done 95 echo --- 96 97 echo 'IFS=":", using $@' 98 c=0 99 for i in $@ 100 do echo "$((c+=1)): [$i]" 101 done 102 echo --- 103 104 var=$@ 105 echo 'IFS=":", using $var (var=$@)' 106 c=0 107 for i in $var 108 do echo "$((c+=1)): [$i]" 109 done 110 echo --- 111 112 echo 'IFS=":", using "$var" (var=$@)' 113 c=0 114 for i in "$var" 115 do echo "$((c+=1)): [$i]" 116 done 117 echo --- 118 119 var="$@" 120 echo 'IFS=":", using "$var" (var="$@")' 121 c=0 122 for i in "$var" 123 do echo "$((c+=1)): [$i]" 124 done 125 echo --- 126 127 echo 'IFS=":", using $var (var="$@")' 128 c=0 129 for i in $var 130 do echo "$((c+=1)): [$i]" 131 done 132 133 echo 134 135 # Try this script with ksh or zsh -y. 136 137 exit 0 |
The $@ and $* parameters differ only when between double quotes. |
Example 9-7. $* and $@ when $IFS is empty
1 #!/bin/bash 2 3 # If $IFS set, but empty, 4 # then "$*" and "$@" do not echo positional params as expected. 5 6 mecho () # Echo positional parameters. 7 { 8 echo "$1,$2,$3"; 9 } 10 11 12 IFS="" # Set, but empty. 13 set a b c # Positional parameters. 14 15 mecho "$*" # abc,, 16 mecho $* # a,b,c 17 18 mecho $@ # a,b,c 19 mecho "$@" # a,b,c 20 21 # The behavior of $* and $@ when $IFS is empty depends 22 # on whatever Bash or sh version being run. 23 # It is therefore inadvisable to depend on this "feature" in a script. 24 25 26 # Thanks, S.C. 27 28 exit 0 |
Other Special Parameters
Flags passed to script
This was originally a ksh construct adopted into Bash, and unfortunately it does not seem to work reliably in Bash scripts. One possible use for it is to have a script self-test whether it is interactive. |
PID (process id) of last job run in background
Special variable set to last argument of previous command executed.
exit status of a command, function, or the script itself (see Example 23-3)
process id of script, often used in scripts to construct temp file names (see Example A-8, Example 30-5, and Example 12-22)
[1] | The pid of the currently running script is $$, of course. |
[2] | The words "argument" and "parameter" are often used interchangeably. In the context of this document, they have the same precise meaning, that of a variable passed to a script or function. |