|
Kansas State University at Salina Introduction to Unix |
|
Several system defined variables are set for you when you log in. You may also define new variables within your shell or shell script program. Variables to the shell are created using a simple assignment statement with no spaces:
variableName=value
me=$(whoami)
echo "Hi, my name is $(getent passwd $me | cut -d: -f5)."
Note
NAMEs are marked for automatic export to the environment of subsequently executed commands.
SYNOPSIS
export [name[=value] ...]
Existing variables may be exported. Variables may also exported as their value is assigned.
me=$(whoami)
export me
export today=$(date)
Set, display or remove variables in the shell environment.
SYNOPSIS
env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]
OPTIONS
If no COMMAND, print the resulting environment.
Arguments or variables may be passed to a shell script. Simply list the arguments on the command line when running a shell script. In the shell script, $0 is the name of the command run (usually the name of the shell script file); $1 is the first argument, $2 is the second argument, $3 is the third argument, etc...
Now for something subtle...
The commands echo $* and echo $@ both print the same thing, the list of all command line arguments, but “$*” is one string, and “$@” is a list of separate strings for each parameter. Consider the following two examples to see how these two similar variables differ. In both cases, the shell script file is ran with three simple command line arguments as ./myscript a b c.
for i in "$*"
do
echo $i
done
Results in:
a b c
Now here is:
for i in "$@"
do
echo $i
done
which displays:
a
b
c
Note
The variable $# reports the number of command line arguments passed to the shell script program.
Cause all of the positional parameters $2 to $n to be renamed $1 to $(n-1), and $1 to be lost.
SYNOPSIS
shift
Here is an example that just displays all of the command line arguments:
while [ ! -z $1 ]
do
echo $1
shift
done
Note
Testing of string variables and shell script control constructs are covered later.
Linux for Programmers and Users, Section 5.21.
When a program is ran, the success or failure of the program may be determined by evaluating the variable $?. An exit value of 0 (zero) means the program was successful, and a nonzero exit value (usually 1) indicates failure.
Return an exit value from a shell script.
SYNOPSIS
exit [n]
Note
When writing programs in C for Unix, it is customary for main() to return an integer (int) value. Zero (0) for success and 1 for failure.