Shell script 的默认变数($0, $1
…)
我们知道指令可以带有选项与参数,例如 ls -la 可以察看包含隐藏文件的所有属性与权限。那么 shell script 能不能在脚本档名后面带有参数呢?很有趣喔!举例来说,如果你想要重新启动系统的网络,可以这样做:
[dmtsai@study ~]$ file /etc/init.d/network
/etc/init.d/network: Bourne-Again shell script, ASCII text executable
# 使用 file 来查询后,系统告知这个文件是个 bash 的可执行 script 喔!
[dmtsai@study ~]$ /etc/init.d/network restart
restart 是重新启动的意思,上面的指令可以『重新启动 /etc/init.d/network 这支程序』的意思! 唔!那么如果你在 /etc/init.d/network 后面加上 stop 呢?没错!就可以直接关闭该服务了!如果你要依据程序的执行给予一些变量去进行不同的任务时,本章一开始是使用 read 的功能!但 read 功能的问题是你得要手动由键盘输入一些判断式。如果透过指令后面接参数, 那么一个指令就能够处理完毕而不需要手动再次输入一些变量行为!这样下达指令会比较简单方便啦!
/path/to/scriptname opt1 opt2 opt3 opt4
$0 $1 $2 $3 $4
这样够清楚了吧?执行的脚本档名为 $0
这个变量,第一个接的参数就是 $1
啊~ 所以,只要我们在 script 里面善用 $1
的话,就可以很简单的立即下达某些指令功能了!除了这些数字的变量之外, 我们还有一些较为特殊的变量可以在 script 内使用来呼叫这些参数喔!
$# ::代表后接的参数『 个』,以上为例这里显示『 4 』
$@ :代表『 "$1" 2" 3" 4" 』之意,每个变量是独立的 (用双引号括起来 );
$* :代表『 "$1 c$2 c$3 c$4" $4" 』,其中 c 为分隔字符, 默认空格键为分隔字符, 所以本例中代表『 "$1 $2 $3 $4" 』 之意。
那个 $@
与 $*
基本上还是有所不同啦!不过,一般使用情况下可以直接记忆 $@
即可! 好了,来做个例子吧~假设我要执行一个可以携带参数的 script ,执行该脚本后屏幕会显示如下的数据:
程序的文件名为何?
共有几个参数?
若参数的个小于 2 则告知使用者参数量太少
全部的参数内容为何?
第一个参数为何?
第二个参数为何
[dmtsai@study bin]$ vim how_paras.sh
#!/bin/bash
# Program:
# Program shows the script name, parameters...
# History:
# 2015/07/16 VBird First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo "The script name is ==> ${0}"
echo "Total parameter number is ==> $#"
[ "$#" -lt 2 ] && echo "The number of parameter is less than 2. Stop here." && exit 0
echo "Your whole parameter is ==> '$@'"
echo "The 1st parameter ==> ${1}"
echo "The 2nd parameter ==> ${2}"
执行结果如下:
[dmtsai@study bin]$ sh how_paras.sh theone haha quot
The script name is ==> how_paras.sh <==檔名
Total parameter number is ==> 3 <==果然有三个参数
Your whole parameter is ==> 'theone haha quot' <==参数的内容全部
The 1st parameter ==> theone <==第一个参数
The 2nd parameter ==> haha <==第二个参数