variables affecting bash script behavior
the path to the Bash binary itself
|
an environmental variable pointing to a Bash startup file to be read when a script is invoked
a variable indicating the subshell level. This is a new addition to Bash, version 3.
See Example 20-1 for usage.
a 6-element array
containing version information about the installed release
of Bash. This is similar to
# Bash version info:
for n in 0 1 2 3 4 5
do
echo "BASH_VERSINFO[$n] = ${BASH_VERSINFO[$n]}"
done
# BASH_VERSINFO[0] = 3 # Major version no.
# BASH_VERSINFO[1] = 00 # Minor version no.
# BASH_VERSINFO[2] = 14 # Patch level.
# BASH_VERSINFO[3] = 1 # Build version.
# BASH_VERSINFO[4] = release # Release status.
# BASH_VERSINFO[5] = i386-redhat-linux-gnu # Architecture
# (same as $MACHTYPE). |
the version of Bash installed on the system
|
|
Checking $BASH_VERSION is a good method of determining which shell is running. $SHELL does not necessarily give the correct answer.
the top value in the directory stack (affected by pushd and popd)
This builtin variable corresponds to the dirs command, however dirs shows the entire contents of the directory stack.
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 |
name of the current function
xyz23 ()
{
echo "$FUNCNAME now executing." # xyz23 now executing.
}
xyz23
echo "FUNCNAME = $FUNCNAME" # FUNCNAME =
# Null value outside a function. |
See also Example A-46.
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
|
home directory of the user, usually
The hostname command
assigns the system host name at bootup in an init script.
However, the
host type
Like $MACHTYPE, identifies the system hardware.
|
internal field separator
This variable determines how Bash recognizes fields, or word boundaries, when it interprets character strings.
$IFS 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
|
(Many thanks, Stéphane Chazelas, for clarification and examples.)
See also Example 15-41, Example 10-7, and Example 18-14
for instructive examples of using
ignore EOF: how many end-of-files (control-D) the shell will ignore before logging out.
Often set in the
![]() | 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 |
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.
# *** BEGIN DEBUG BLOCK *** last_cmd_arg=$_ # Save it. echo "At line number $LINENO, variable \"v1\" = $v1" echo "Last command argument processed = $last_cmd_arg" # *** END DEBUG BLOCK *** |
machine type
Identifies the system hardware.
|
old working directory ("OLD-print-working-directory", previous directory you were in)
operating system type
|
path to binaries, usually
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,
|
![]() | The current "working directory",
|
Array variable holding exit status(es) of last executed foreground pipe. Interestingly enough, this does not necessarily give the same result as the exit status of the last executed command.
|
The members of the
![]() | The
The above lines contained in a script would produce the expected
Thank you, Wayne Pollock for pointing this out and supplying the above example. |
![]() | The
Chet Ramey attributes the above output to the behavior of
ls. If ls
writes to a pipe whose output is not
read, then |
![]() |
|
![]() | The pipefail option
may be useful in cases where
|
The
Compare this with the pidof command.
A variable holding a command to be executed
just before the primary prompt,
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-29).
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.
#!/bin/bash E_WRONG_DIRECTORY=83 clear # Clear screen. TargetDirectory=/home/bozo/projects/GreatAmericanNovel cd $TargetDirectory echo "Deleting stale files in $TargetDirectory." if [ "$PWD" != "$TargetDirectory" ] then # Keep from wiping out wrong directory by accident. echo "Wrong directory!" echo "In $PWD, rather than $TargetDirectory!" echo "Bailing out!" exit $E_WRONG_DIRECTORY fi rm -rf * rm .[A-Za-z0-9]* # Delete dotfiles. # rm -f .[^.]* ..?* to remove filenames beginning with multiple dots. # (shopt -s dotglob; rm -f *) will also work. # Thanks, S.C. for pointing this out. # A filename (`basename`) may contain all characters in the 0 - 255 range, #+ except "/". # Deleting files beginning with weird characters, such as - #+ is left as an exercise. echo echo "Done." echo "Old files deleted in $TargetDirectory." echo # Various other operations here, as necessary. exit $? |
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.
#!/bin/bash # reply.sh # REPLY is the default value for a 'read' command. echo echo -n "What is your favorite vegetable? " read echo "Your favorite vegetable is $REPLY." # REPLY holds the value of last "read" if and only if #+ no variable supplied. echo echo -n "What is your favorite fruit? " read fruit echo "Your favorite fruit is $fruit." echo "but..." echo "Value of \$REPLY is still $REPLY." # $REPLY is still set to its previous value because #+ the variable $fruit absorbed the new "read" value. echo exit 0 |
The number of seconds the script has been running.
#!/bin/bash
TIME_LIMIT=10
INTERVAL=1
echo
echo "Hit Control-C to exit before $TIME_LIMIT seconds."
echo
while [ "$SECONDS" -le "$TIME_LIMIT" ]
do
if [ "$SECONDS" -eq 1 ]
then
units=second
else
units=seconds
fi
echo "This script has been running $SECONDS $units."
# On a slow or overburdened machine, the script may skip a count
#+ every once in a while.
sleep $INTERVAL
done
echo -e "\a" # Beep!
exit 0 |
the list of enabled shell options, a readonly variable
|
Shell level, how deeply Bash is nested. [2] If, at the command line, $SHLVL is 1, then in a script it will increment to 2.
![]() | This variable is not affected by subshells. Use $BASH_SUBSHELL when you need an indication of subshell nesting. |
If the
As of version 2.05b of Bash, it is now possible to use
# Works in scripts for Bash, versions 2.05b and later. TMOUT=3 # Prompt times out at three seconds. echo "What is your favorite song?" echo "Quickly now, you only have $TMOUT seconds to answer!" read song if [ -z "$song" ] then song="(no answer)" # Default response. fi echo "Your favorite song is $song." |
There are other, more complex, ways of implementing timed input in a script. One alternative 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 29-5) the interrupt generated by the timing loop (whew!).
Example 9-2. Timed Input
#!/bin/bash
# timed-input.sh
# TMOUT=3 Also works, as of newer versions of Bash.
TIMER_INTERRUPT=14
TIMELIMIT=3 # Three seconds in this instance.
# May be set to different value.
PrintAnswer()
{
if [ "$answer" = TIMEOUT ]
then
echo $answer
else # Don't want to mix up the two instances.
echo "Your favorite veggie is $answer"
kill $! # Kills no-longer-needed TimerOn function
#+ running in background.
# $! is PID of last job running in background.
fi
}
TimerOn()
{
sleep $TIMELIMIT && kill -s 14 $$ &
# Waits 3 seconds, then sends sigalarm to script.
}
Int14Vector()
{
answer="TIMEOUT"
PrintAnswer
exit $TIMER_INTERRUPT
}
trap Int14Vector $TIMER_INTERRUPT
# Timer interrupt (14) subverted for our purposes.
echo "What is your favorite vegetable "
TimerOn
read answer
PrintAnswer
# Admittedly, this is a kludgy implementation of timed input.
# However, the "-t" option to "read" simplifies this task.
# See the "t-out.sh" script.
# However, what about timing not just single user input,
#+ but an entire script?
# If you need something really elegant ...
#+ consider writing the application in C or C++,
#+ using appropriate library functions, such as 'alarm' and 'setitimer.'
exit 0 |
An alternative is using stty.
Example 9-3. Once more, timed input
#!/bin/bash
# timeout.sh
# Written by Stephane Chazelas,
#+ and modified by the document author.
INTERVAL=5 # timeout interval
timedout_read() {
timeout=$1
varname=$2
old_tty_settings=`stty -g`
stty -icanon min 0 time ${timeout}0
eval read $varname # or just read $varname
stty "$old_tty_settings"
# See man page for "stty".
}
echo; echo -n "What's your name? Quick! "
timedout_read $INTERVAL your_name
# This may not work on every terminal type.
# The maximum timeout depends on the terminal.
#+ (it is often 25.5 seconds).
echo
if [ ! -z "$your_name" ] # If name input before timeout...
then
echo "Your name is $your_name."
else
echo "Timed out."
fi
echo
# The behavior of this script differs somewhat from "timed-input.sh".
# At each keystroke, the counter resets.
exit 0 |
Perhaps the simplest method is using the
Example 9-4. Timed read
#!/bin/bash # t-out.sh # Inspired by a suggestion from "syngin seven" (thanks). TIMELIMIT=4 # 4 seconds read -t $TIMELIMIT variable <&1 # ^^^ # In this instance, "<&1" is needed for Bash 1.x and 2.x, # but unnecessary for Bash 3.x. echo if [ -z "$variable" ] # Is null? then echo "Timed out, variable still unset." else echo "variable = $variable" fi exit 0 |
user ID number
Current user's user identification number, as
recorded in
This is the current user's real id, even if she has
temporarily assumed another identity through su.
Example 9-5. Am I root?
#!/bin/bash # am-i-root.sh: Am I root or not? ROOT_UID=0 # Root has $UID 0. if [ "$UID" -eq "$ROOT_UID" ] # Will the real "root" please stand up? then echo "You are root." else echo "You are just an ordinary user (but mom loves you just the same)." fi exit 0 # ============================================================= # # Code below will not execute, because the script already exited. # An alternate method of getting to the root of matters: ROOTUSER_NAME=root username=`id -nu` # Or... username=`whoami` if [ "$username" = "$ROOTUSER_NAME" ] then echo "Rooty, toot, toot. You are root." else echo "You are just a regular fella." fi |
See also Example 2-3.
![]() | The variables
|
Positional Parameters
Positional parameters, passed from command line to script, passed to a function, or set to a variable (see Example 4-5 and Example 14-16)
Number of command line arguments [3] or positional parameters (see Example 33-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.
![]() | Of course, " |
Example 9-6. arglist: Listing arguments with $* and $@
#!/bin/bash
# arglist.sh
# Invoke this script with several arguments, such as "one two three".
E_BADARGS=65
if [ ! -n "$1" ]
then
echo "Usage: `basename $0` argument1 argument2 etc."
exit $E_BADARGS
fi
echo
index=1 # Initialize count.
echo "Listing args with \"\$*\":"
for arg in "$*" # Doesn't work properly if "$*" isn't quoted.
do
echo "Arg #$index = $arg"
let "index+=1"
done # $* sees all arguments as single word.
echo "Entire arg list seen as single word."
echo
index=1 # Reset count.
# What happens if you forget to do this?
echo "Listing args with \"\$@\":"
for arg in "$@"
do
echo "Arg #$index = $arg"
let "index+=1"
done # $@ sees arguments as separate words.
echo "Arg list seen as separate words."
echo
index=1 # Reset count.
echo "Listing args with \$* (unquoted):"
for arg in $*
do
echo "Arg #$index = $arg"
let "index+=1"
done # Unquoted $* sees arguments as separate words.
echo "Arg list seen as separate words."
exit 0 |
Following a shift, the
#!/bin/bash # Invoke with ./scriptname 1 2 3 4 5 echo "$@" # 1 2 3 4 5 shift echo "$@" # 2 3 4 5 shift echo "$@" # 3 4 5 # Each "shift" loses parameter $1. # "$@" then contains the remaining parameters. |
The
![]() | The |
Example 9-7. Inconsistent
#!/bin/bash
# Erratic behavior of the "$*" and "$@" internal Bash variables,
#+ depending on whether they are quoted or not.
# Inconsistent handling of word splitting and linefeeds.
set -- "First one" "second" "third:one" "" "Fifth: :one"
# Setting the script arguments, $1, $2, etc.
echo
echo 'IFS unchanged, using "$*"'
c=0
for i in "$*" # quoted
do echo "$((c+=1)): [$i]" # This line remains the same in every instance.
# Echo args.
done
echo ---
echo 'IFS unchanged, using $*'
c=0
for i in $* # unquoted
do echo "$((c+=1)): [$i]"
done
echo ---
echo 'IFS unchanged, using "$@"'
c=0
for i in "$@"
do echo "$((c+=1)): [$i]"
done
echo ---
echo 'IFS unchanged, using $@'
c=0
for i in $@
do echo "$((c+=1)): [$i]"
done
echo ---
IFS=:
echo 'IFS=":", using "$*"'
c=0
for i in "$*"
do echo "$((c+=1)): [$i]"
done
echo ---
echo 'IFS=":", using $*'
c=0
for i in $*
do echo "$((c+=1)): [$i]"
done
echo ---
var=$*
echo 'IFS=":", using "$var" (var=$*)'
c=0
for i in "$var"
do echo "$((c+=1)): [$i]"
done
echo ---
echo 'IFS=":", using $var (var=$*)'
c=0
for i in $var
do echo "$((c+=1)): [$i]"
done
echo ---
var="$*"
echo 'IFS=":", using $var (var="$*")'
c=0
for i in $var
do echo "$((c+=1)): [$i]"
done
echo ---
echo 'IFS=":", using "$var" (var="$*")'
c=0
for i in "$var"
do echo "$((c+=1)): [$i]"
done
echo ---
echo 'IFS=":", using "$@"'
c=0
for i in "$@"
do echo "$((c+=1)): [$i]"
done
echo ---
echo 'IFS=":", using $@'
c=0
for i in $@
do echo "$((c+=1)): [$i]"
done
echo ---
var=$@
echo 'IFS=":", using $var (var=$@)'
c=0
for i in $var
do echo "$((c+=1)): [$i]"
done
echo ---
echo 'IFS=":", using "$var" (var=$@)'
c=0
for i in "$var"
do echo "$((c+=1)): [$i]"
done
echo ---
var="$@"
echo 'IFS=":", using "$var" (var="$@")'
c=0
for i in "$var"
do echo "$((c+=1)): [$i]"
done
echo ---
echo 'IFS=":", using $var (var="$@")'
c=0
for i in $var
do echo "$((c+=1)): [$i]"
done
echo
# Try this script with ksh or zsh -y.
exit 0
# This example script by Stephane Chazelas,
# and slightly modified by the document author. |
![]() | The $@ and $* parameters differ only when between double quotes. |
Example 9-8.
#!/bin/bash
# If $IFS set, but empty,
#+ then "$*" and "$@" do not echo positional params as expected.
mecho () # Echo positional parameters.
{
echo "$1,$2,$3";
}
IFS="" # Set, but empty.
set a b c # Positional parameters.
mecho "$*" # abc,,
mecho $* # a,b,c
mecho $@ # a,b,c
mecho "$@" # a,b,c
# The behavior of $* and $@ when $IFS is empty depends
#+ on whatever Bash or sh version being run.
# It is therefore inadvisable to depend on this "feature" in a script.
# Thanks, Stephane Chazelas.
exit 0 |
Other Special Parameters
Flags passed to script (using set). See Example 14-16.
![]() | 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
LOG=$0.log
COMMAND1="sleep 100"
echo "Logging PIDs background commands for script: $0" >> "$LOG"
# So they can be monitored, and killed as necessary.
echo >> "$LOG"
# Logging commands.
echo -n "PID of \"$COMMAND1\": " >> "$LOG"
${COMMAND1} &
echo $! >> "$LOG"
# PID of "sleep 100": 1506
# Thank you, Jacques Lederer, for suggesting this. |
Using
possibly_hanging_job & { sleep ${TIMEOUT}; eval 'kill -9 $!' &> /dev/null; }
# Forces completion of an ill-behaved program.
# Useful, for example, in init scripts.
# Thank you, Sylvain Fourmanoit, for this creative use of the "!" variable. |
Or, alternately:
# This example by Matthew Sage.
# Used with permission.
TIMEOUT=30 # Timeout value in seconds
count=0
possibly_hanging_job & {
while ((count < TIMEOUT )); do
eval '[ ! -d "/proc/$!" ] && ((count = TIMEOUT))'
# /proc is where information about running processes is found.
# "-d" tests whether it exists (whether directory exists).
# So, we're waiting for the job in question to show up.
((count++))
sleep 1
done
eval '[ -d "/proc/$!" ] && kill -15 $!'
# If the hanging job is running, kill it.
} |
Special variable set to last argument of previous command executed.
Exit status of a command, function, or the script itself (see Example 23-7)
Process ID of the script itself. The
| [1] | The PID of the currently running script is
|
| [2] | Somewhat analogous to recursion, in this context nesting refers to a pattern embedded within a larger pattern. One of the definitions of nest, according to the 1913 edition of Webster's Dictionary, illustrates this beautifully: "A collection of boxes, cases, or the like, of graduated size, each put within the one next larger." |
| [3] | The words "argument" and "parameter" are often used interchangeably. In the context of this document, they have the same precise meaning: a variable passed to a script or function. |