Shell passing parameters
We can pass parameters to the script when executing the Shell script. The format for obtaining parameters in the script is: $n. n represents a number, 1 is the first parameter to execute the script, 2 is the second parameter to execute the script, and so on...
Example
The following In the example, we pass three parameters to the script and output them respectively, where $0 is the file name to be executed:
#!/bin/bash # author:php中文网 # url:www.php.cn echo "Shell 传递参数实例!"; echo "执行的文件名:$ chmod +x test.sh $ ./test.sh 1 2 3 Shell 传递参数实例! 执行的文件名:test.sh 第一个参数为:1 第二个参数为:2 第三个参数为:3"; echo "第一个参数为:"; echo "第二个参数为:"; echo "第三个参数为:";
Set executable permissions for the script and execute the script. The output result is as follows :
#!/bin/bash # author:php中文网 # url:www.php.cn echo "Shell 传递参数实例!"; echo "第一个参数为:"; echo "参数个数为:$#"; echo "传递的参数作为一个字符串显示:$*";
In addition, there are several special characters used to process parameters:
Parameter processing | Description |
---|---|
$ | #The number of parameters passed to the script |
$* | Displays all directions as a single string Parameters passed by the script. If "$*" is enclosed in """, all parameters will be output in the form of "$1 $2 ... $n". |
$$ | The current process ID number of the script running |
$! | Running in the background The ID number of the last process |
$@ | is the same as $*, but is used in quotes and returns each parameter in quotes. If "$@" is enclosed in """, all parameters will be output in the form of "$1" "$2" ... "$n". |
$- | Displays the current options used by the Shell, which has the same function as the set command. |
$? | Displays the exit status of the last command. 0 indicates no error, any other value indicates an error. |
$ chmod +x test.sh $ ./test.sh 1 2 3 Shell 传递参数实例! 第一个参数为:1 参数个数为:3 传递的参数作为一个字符串显示:1 2 3
Execute the script, the output result is as follows:
#!/bin/bash # author:php中文网 # url:www.php.cn echo "-- $* 演示 ---" for i in "$*"; do echo $i done echo "-- $@ 演示 ---" for i in "$@"; do echo $i done
$* and $@ Difference:
Same point: all parameters are quoted.
Difference: only reflected in double quotes. Assume that three parameters 1, 2, and 3 are written when the script is running, then " * " is equivalent to "1 2 3" (one parameter is passed), and "@" is equivalent to "1" "2" " 3" (three parameters passed).
$ chmod +x test.sh $ ./test.sh 1 2 3 -- $* 演示 --- 1 2 3 -- $@ 演示 --- 1 2 3
Execute the script, the output result is as follows:
rrreee