In conjunction with variables we have arguments. We are interested in knowing how argument values are transferred to variables.
Arguments are the objects given with the command on the command line
mycopy file1 file2
On another occasion the arguments might be file42 and prog42. The arguments are variable values given at the invocation of the program. They do not differ from any other variable in the OS.
The first argument received by the program is know in the script
as $1, the next is $2, …
$9.
#!/bin/bash
# Written by Niels ML, dato 8.4.98
# Maintained on
# This program copies a file
# It takes the arguments:
# filename1 filename2
# where filename1 is input and
# filename2 is the output
# kopi filename1 filename2
case $# in
0 | 1) echo 'Usage: mycopy file file|dir'; exit 1
esac
cp $1 $2
echo $0: $1 has now been copied
echo $0: $2 is the name of the copy.
I hear you asking, whatever is $0?
It is the first item on the command line, the name of the program:
nml@mymb ~/bin $ cat -n testpos
1 #!/bin/bash
2 echo "I am $0"
3 echo "My arguments are $@"
4 echo "My first four positional arguments are $1 $2 $3 $4"
5 echo " "
6
7 shift
8 echo "My argumentlist is now $@"
9 echo "My first four positional arguments are $1 $2 $3 $4"
10 echo " "
11
12 shift 3
13 echo "My argumentlist is now $@"
14 echo "My first four positional arguments are $1 $2 $3 $4"
15
nml@mymb ~/bin $ sh testpos first second third fourth fifth sixth seventh
I am testpos
My arguments are first second third fourth fifth sixth seventh
My first four positional arguments are first second third fourth
My argumentlist is now second third fourth fifth sixth seventh
My first four positional arguments are second third fourth fifth
My argumentlist is now fifth sixth seventh
My first four positional arguments are fifth sixth seventh
nml
1 #!/bin/bash
2 echo "I am $0"
3 echo "My arguments are $@"
4 echo "My first four positional arguments are $1 $2 $3 $4"
5 echo " "
6
7 shift
8 echo "My argumentlist is now $@"
9 echo "My first four positional arguments are $1 $2 $3 $4"
10 echo " "
11
12 shift 3
13 echo "My argumentlist is now $@"
14 echo "y first four positional arguments are $1 $2 $3 $4"