Shell passing parameters
We can pass parameters to the script when executing the Shell script. The format of the parameters obtained 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
In the following example, we pass three parameters to the script and output them separately, where $0 is the filename to be executed:
#!/bin/bash # author:Rookie Tutorial # url:www.runoob.com echo "Shell passing parameter instance!" ; echo "Executed file name: $0" ; echo "The first parameter is: $1" ; echo "The second parameter is: $2" ; echo "The third parameter is: $3 " ;
Set executable permissions for the script and execute the script. The output is as follows:
$ chmod +x test.sh $ ./test .sh 1 2 3 Shell pass parameter instance ! Executed file name: ./test.sh The first parameter is: 1 The second parameter is: 2 The third parameter is: 3
In addition, there are several special characters used to process parameters:
parameter handling | illustrate |
---|---|
$# | The number of arguments passed to the script |
$* | Displays all parameters passed to the script as a single string. For example, when "$*" is enclosed in """, all parameters are output in the form of "$1 $2 ... $n". |
$$ | The current process ID number of the script running |
$! | ID number of the last process running in the background |
$@ | Same as $*, but used with quotes, returning each argument in quotes. For example, when "$@" is enclosed in """, all parameters are 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 means no error, any other value means there is an error. |
#!/bin/bash # author:Rookie Tutorial # url:www.runoob.com echo "Shell 传递参数实例!"; echo "第一个参数为:$1"; echo "参数个数为:$#"; echo "传递的参数作为一个字符串显示:$*";
执行脚本,输出结果如下所示:
$ chmod +x test.sh $ ./test.sh 1 2 3 Shell 传递参数实例! 第一个参数为:1 参数个数为:3 传递的参数作为一个字符串显示:1 2 3
$* 与 $@ 区别:
- 相同点:都是引用所有参数。
- 不同点:只有在双引号中体现出来。假设在脚本运行时写了三个参数 1、2、3,,则 " * " 等价于 "1 2 3"(传递了一个参数),而 "@" 等价于 "1" "2" "3"(传递了三个参数)。
#!/bin/bash # author:菜鸟教程 # url:www.runoob.com echo "-- \$* 演示 ---" for i in "$*"; do echo $i done echo "-- \$@ 演示 ---" for i in "$@"; do echo $i done
执行脚本,输出结果如下所示:
$ chmod +x test.sh $ ./test.sh 1 2 3 -- $* 演示 --- 1 2 3 -- $@ 演示 --- 1 2 3
墓志铭
muz***[email protected]
在为shell脚本传递的参数中如果包含空格,应该使用单引号或者双引号将该参数括起来,以便于脚本将这个参数作为整体来接收。
在有参数时,可以使用对参数进行校验的方式处理以减少错误发生:
注意:的是中括号 [] 与其中间的代码应该有空格隔开