The shell passes the parameters

We can pass parameters to the script when we execute the Shell script, and the format in which the parameters are obtained within the script is: $n. n represents a number, 1 is the first argument to execute the script, 2 is the second argument to execute the script, and so on...

Instance

In the following example, we pass three parameters to the script and output them separately, where $0 is the file name of the execution:

#!/bin/bash
# author:W3Cschool教程
# url:www.w3cschool.cn

echo "Shell 传递参数实例!";
echo "执行的文件名:$0";
echo "第一个参数为:$1";
echo "第二个参数为:$2";
echo "第三个参数为:$3";

Set up executable permissions for the script and execute the script, and the output looks like this:

$ chmod +x test.sh 
$ ./test.sh 1 2 3
Shell 传递参数实例!
执行的文件名:test.sh
第一个参数为:1
第二个参数为:2
第三个参数为:3

In addition, there are several special characters for handling parameters:

Argument processing Description
$# The number of parameters passed to the script
$* Displays all parameters passed to the script in a single string.
If "$" is enclosed with "", all parameters are output in the form of "$1 $2 ... $n".
$$ The current process ID number that the script is running
$! The ID number of the last process running in the background
$@ Same as $, but with quotation marks, and returns each argument in quotation marks.
For example, "$" is enclosed with "" and "$1" "$2" ... O utput$ $n parameters in the form of $n" .
$- Displays the current options used by Shell, which is the same as the set command feature.
$? Displays the exit status of the last command. 0 indicates no error, and any other value indicates an error.
#!/bin/bash
# author:W3Cschool教程
# url:www.w3cschool.cn

echo "Shell 传递参数实例!";
echo "第一个参数为:$1";

echo "参数个数为:$#";
echo "传递的参数作为一个字符串显示:$*";

Execute the script and the output looks like this:

$ chmod +x test.sh 
$ ./test.sh 1 2 3
Shell 传递参数实例!
第一个参数为:1
参数个数为:3
传递的参数作为一个字符串显示:1 2 3

The difference between $? and $?

  • Same thing: all parameters are referenced.
  • Difference: Only in double quotes. S uppose you write three parameters 1, 2, 3 while the script is running, then """ is equivalent to "1 2 3" (a parameter is passed) and "" is equivalent to "1" "2" "3" (three parameters are passed).
#!/bin/bash
# author:W3Cschool教程
# url:www.w3cschool.cn

echo "-- \$* 演示 ---"
for i in "$*"; do
    echo $i
done

echo "-- \$@ 演示 ---"
for i in "$@"; do
    echo $i
done

Execute the script and the output looks like this:

$ chmod +x test.sh 
$ ./test.sh 1 2 3
-- $* 演示 ---
1 2 3
-- $@ 演示 ---
1
2
3