Shell Passing Arguments
When executing a Shell script, we can pass parameters to the script. The format for obtaining parameters within the script is:$n,nrepresents a number,1is the first parameter of the executed script,2is the second parameter of the executed script.
For example, you can use$1、$2etc. to reference the parameters passed to the script, where$1represents the first parameter,$2represents the second parameter, and so on.
Example
In the following example, we pass three parameters to the script and output them separately, where$0is the name of the executed file (including the file path):
Example
# author: Example
# url:www.example.com
echo "Shell passing parameters example!";
echo "File name executed: $0";
echo "The first parameter is: $1";
echo "The second parameter is: $2";
echo "The third parameter is: $3";
Set executable permission for the script and execute it. The output is as follows:
$ chmod +x test.sh $ ./test.sh 1 2 3 Shell 传递参数实例! 执行的文件名:./test.sh 第一个参数为:1 第二个参数为:2 第三个参数为:3
In addition, there are several special characters used to handle parameters:
| Parameter handling | Description |
|---|---|
| $# | Number of parameters passed to the script |
| $* | Displays all parameters passed to the script as a single string. For example, when "$*" is enclosed in double quotes, it outputs all parameters in the form "$1 $2 … $n". |
| $$ | The current process ID of the script running |
| $! | The ID of the last process running in the background |
| $@ | Same as $*, but each parameter is quoted when used; it returns each parameter in quotes. For example, when "$@" is enclosed in double quotes, it outputs all parameters in the form "$1" "$2" … "$n". |
| $- | Displays the current options used by Shell, which is the same asthe set commandin function. |
| $? | Displays the exit status of the last command. 0 means no error, any other value indicates an error. |
Example
# author: Example
# url:www.example.com
echo "Shell passing parameters example!";
echo "The first parameter is: $1";
echo "The number of parameters is: $#";
echo "The parameters passed are displayed as a string: $*";
Execute the script, and the output is as follows:
$ chmod +x test.sh $ ./test.sh 1 2 3 Shell 传递参数实例! 第一个参数为:1 参数个数为:3 传递的参数作为一个字符串显示:1 2 3
Difference between $* and $@:
- Same: both reference all parameters.
- Difference: it is only reflected when enclosed in double quotes. Suppose three parameters 1, 2, 3 are written when the script runs, then "$*" is equivalent to "1 2 3" (one parameter passed), while "$@" is equivalent to "1" "2" "3" (three parameters passed).
Example
# author: Example
# url:www.example.com
echo "-- \$* Demo ---
for i in "$*"; do
echo $i
done
echo "-- \$@ Demo ---
for i in "$@"; do
echo $i
done
Execute the script, and the output is as follows:
$ chmod +x test.sh $ ./test.sh 1 2 3 -- $* 演示 --- 1 2 3 -- $@ 演示 --- 1 2 3Other Extensions