Shell Passing Arguments
We can pass arguments to a Shell script when executing it, and the script retrieves the arguments in the format: $n. n represents a number, where 1 is the first parameter of the script, 2 is the second parameter, and so on...
Example
In the following example, we pass three parameters to the script and output them separately, where $0 is the filename of the script (including the file path):
Example
#!/bin/bash
# author:tutorialpro.org
# url:www.tutorialpro.org
echo "Shell Passing Arguments Example!";
echo "Executed filename: $0";
echo "First parameter: $1";
echo "Second parameter: $2";
echo "Third parameter: $3";
Set the executable permission for the script and execute it, the output is as follows:
$ chmod +x test.sh
$ ./test.sh 1 2 3
Shell Passing Arguments Example!
Executed filename: ./test.sh
First parameter: 1
Second parameter: 2
Third parameter: 3
Additionally, there are several special characters used to handle parameters:
Parameter Handling | Description |
---|---|
$# | Number of arguments passed to the script |
$* | Displays all arguments passed to the script as a single string. <br>For example, "$*" enclosed in quotes, outputs all parameters as "$1 $2 … $n". |
$$ | The current process ID number of the script |
$! | The process ID number of the last background process |
$@ | Same as $*, but quoted, each parameter is returned in quotes. <br>For example, "$@" enclosed in quotes, outputs all parameters as "$1" "$2" … "$n". |
$- | Displays the current options used by the Shell, similar to the set command |
$? | Displays the exit status of the last command. 0 indicates no errors, any other value indicates an error. |
Example
#!/bin/bash
# author:tutorialpro.org
# url:www.tutorialpro.org
echo "Shell Passing Arguments Example!";
echo "First parameter: $1";
echo "Number of parameters: $#";
echo "Parameters displayed as a single string: $*";
Executing the script, the output is as follows:
$ chmod +x test.sh
$ ./test.sh 1 2 3
Shell Passing Arguments Example!
First parameter: 1
Number of parameters: 3
Parameters displayed as a single string: 1 2 3
Difference between $* and $@:
Similarity: Both reference all parameters.
Difference: Only apparent when used within double quotes. If three parameters 1, 2, 3 are provided during script execution, then "*" is equivalent to "1 2 3" (one argument passed), while "@" is equivalent to "1" "2" "3" (three arguments passed).
Example
#!/bin/bash
# author:tutorialpro.org
# url:www.tutorialpro.org
echo "-- \$* Demonstration ---"
for i in "$*"; do
echo $i
done
echo "-- \$@ Demonstration ---"
for i in "$@"; do
echo $i
done
Executing the script, the output is as follows:
$ chmod +x test.sh
$ ./test.sh 1 2 3
-- $* Demonstration ---
1 2 3
-- $@ Demonstration ---
1
2
3