Variables - Part II
Linux offers a set of pre-defined variables. These pre-defined variables contain useful information.
The first set of variables are $0
, $1
, ..., $9
, and $#
.
The variable $0
is the name of the program as it was called. For example, if
you run example.sh
which uses the variable $0
, it will return example.sh
.
$1
, ..., $9
are the first 9 additional parameters the script was called
with. The total number of parameters that the script is called with is stored
in $#
.
To access all parameters at once, we can use $@
and $*
. $@
is a special
variable takes the entire list of parameters and separates them into a list of
parameters. Thus, the variable $@
is all parameters $1
, ...,
$any_number
. The variables $*
is similar but does not preserve any
whitespace or quoting, so "File with spaces" becomes "File" "with" "spaces".
This is similar to the echo command.
Let's do a hands on example.
var4.sh | |
---|---|
1 2 3 4 5 6 |
|
Here is a sample run for the above script.
input | |
---|---|
1 |
|
output | |
---|---|
1 2 3 4 5 6 7 8 |
|
output | |
---|---|
1 2 3 4 5 |
|
$#
and $1
, ..., $9
are set by the shell. We can take more than 9
parameters by using the shift
command. Look at the next example.
test.sh | |
---|---|
1 2 3 4 5 6 |
|
The backslash character \
is used to "escape" $
so that it is not
interpreted by the shell. This script uses shift
to move all parameters down
one slot (removing $1
) until $#
is down to zero.
Here is a sample run for the above script.
input | |
---|---|
1 |
|
output | |
---|---|
1 2 3 4 5 6 7 8 9 |
|
We can write a script using $*
to get the same result.
1 2 3 4 5 6 |
|
In the previous scripts, while
, for
, and do ... done
are loop commands which will be covered
later.
The $?
variable represents the exit status of the previous
command. Exit status is a numerical value returned by every command upon
its completion. Most commands return 0 if they were successful, and 1 if
they were unsuccessful.
test.sh | |
---|---|
1 2 3 4 5 6 7 |
|
Here is the result of the sample run.
input | |
---|---|
1 |
|
output | |
---|---|
1 2 3 4 5 6 7 8 9 10 |
|