Positional Parameters
Positional Parameters are used to pass the information to the shell directly with command line argument or indirectly using set and command substitution. It can be assigned from shell argument and it is denoted by $N, where N is the single digit and referred as parameter N. if N is double digit use braces ${N}.
Command Line Argument for positional Parameters
You can pass many arguments in command line.
For Example we run a script script.sh with 10 argument a to j
Now the detail of output we get from positional parameters
For Example we run a script script.sh with 10 argument a to j
- $ ./script.sh a b c d e f g h i j
Now the detail of output we get from positional parameters
- $0 is the name of script
./script.sh
- $1 is the first parameter passed.
a
- $2 is second parameter passed.
b
- ${10} is the 10 parameter passed, use bracket for double digit
j
- if no bracket is used i.e. $10 then the output is
a0
- $@ lists all positional parameters, it sees parameters as different words.
a b c d e f g h i j
- $* lists all parameter, it sees parameters as a single word if quoted (“$*”). Use IFS to separate the different word. See the last example for this IFS.
a b c d e f g h i j
- $# is the number of parameter passed.
10
In command-line, however, $0 is the name of the shell.
$ $0
-bash
- $? Gives the exit status of most recently executed command.
It gives 0 for successful, or an integer in the range 1 - 255 on error.
Example
let we make a script parameter.sh as below and run the script with four arguments page, linux, dot, com
$ cat parameter.sh
#!/bin/bash
IFS=-
echo $0
echo $1
echo $2
echo $*
echo $#
echo $@
echo "$*"
echo "$@"
echo $?
unset IFS
echo "$*"
After running the script we get the output as
$ sh parameter.sh page linux dot com
./parameter.sh
page
linux
page linux dot com
4
page linux dot com
page-linux-dot-com
page linux dot com
0
page linux dot com
SET Command
Example:
set `who am i`
echo $1
username
Here previously assigned values for positional parameters will be erased!!
echo-command-and-quoting-in-Linux
No comments:
Post a Comment