Page 128 - DCAP106_OPERATING_SYSTEM_TOOLS
P. 128
Unit 7: The Shell
much better. The double quotation marks allowed Bash to substitute the value of $USER, which Notes
is set automatically when you log in, in the string.
Example: This example presents a common error:
costmsg=”Price is $5.00”
echo $costmsg
Actual result: Price is .00
Here, we thought quote the string, however the dollar sign tells Bash to use the value in
the $5 variable, which is not what we required. We can easily solve the problem by prefixing the
dollar sign with a backslash, as shown here:
$ costmsg=”Price is \$5.00”
$ echo $costmsg
Actual result: Price is $5.00
Arguments and Other Special Variables
The values that you pass to a shell script are called arguments. Every value on the command line
after the name of the script will be allocated to the special variables $1, $2, $3, and so on. The
name of the currently running script is stored in the $0 variable.
Some other special variables that are useful in script writing are:
z z $# The number of arguments
z z $* The entire argument string
z z $? The return code from the last command issued
Now we will show some examples working with arguments and other special variables.
Example: Create an executable script called testvars containing these lines:
echo “My name is $0”
echo “First arg is: $1”
echo “Second arg is: $2”
echo “I got a total of $# arguments.”
echo “The full argument string was: $*”
Now if you run this script, here’s what you’ll see:
$ ./testvars birds have lips
My name is testvars
First arg is: birds
Second arg is: have
I got a total of 3 arguments.
The full argument string was: birds have lips
LOVELY PROFESSIONAL UNIVERSITY 121