Here we will see the naming convention of parameters which are passed to a script and how we can use them? how shifting works?
#!/bin/bash
- # Positional parameters
- # $0 $1 $2 $3 ....... $n
- # Command Arg1 Arg2 Arg3 ....... Argn
echo -e "First argument $1, Second argument $2, Third argument $3, Fourth argument $4\n"
- This will print value of all four arguments which you passed, just for your reference.
shift
- The positional parameters from n+1 ... are renamed to $1, so that every time after shift is performed there is a new argument to be processed.
- This will shift to the left by one value.
echo "Shifting...."
echo -e "First argument $1, second argument $2, third argument $3, fourth argument $4 \n"
- This will print new values after shifting the arguments by one value.
shift 2
- This will shift to the left by two values.
echo "Shifting.... by 2 vlaues"
echo -e "First argument $1, second argument $2, third argument $3, fourth argument $4 \n"
Lets see the results now:
sunny@sunny-workstation bin]$ ./4_positional_params.sh android ios meego maemo (arguments)
First argument android, second argument ios, third argument meego, fourth argument maemo
Shifting....
First argument ios, second argument meego, third argument maemo, fourth argument
Shifting.... by 2 vlaues
First argument maemo, second argument , third argument , fourth argument
sunny@sunny-workstation bin]$
More with positional parameters:
- Below are the special positional parameters:
- $# => Total number of arguments.
- $@ => All arguments as a list.
- $* => All arguments as a single value.
Take a simple example for $@ and $*:
- Below is a simple for loop in which values are being passed as arguments.
- When we are using $* it will display all the arguments as a single value.
sunny@sunny-workstation bin]$ cat test.sh
for var in "$*"
do
echo "$var"
done
sunny@sunny-workstation bin]$ ./test.sh 1 2 3 4 5 6
1 2 3 4 5 6
sunny@sunny-workstation bin]$
- Now lets change $* by $@, it will display the output as a list or separate values.
sunny@sunny-workstation bin]$ cat test.sh
for var in "$@"
do
echo "$var"
done
sunny@sunny-workstation bin]$
[bhambhan@sunny-workstation bin]$ ./test.sh 1 2 3 4 5 6
1
2
3
4
5
6
[bhambhan@sunny-workstation bin]$
- Now lets take all three in a single example:
#!/bin/bash
echo -e "$# arguments were passed to the script and they were $@ \n"
echo -e "$* \n"
sunny@sunny-workstation bin]$ ./5_special_positional_params_.sh 1 2 3 4 5 6
6 arguments were passed to the script and they were 1 2 3 4 5 6
1 2 3 4 5 6
sunny@sunny-workstation bin]$
Comments
Post a Comment