Shell script 的默认变数($0, $1...)

$

/path/to/scriptname	opt1 opt2 opt3 opt4
	$0 					$1 	$2 $3 $4

 $# :代表后接的参数『个数』,以上表为例这里显示为『 4 』;
 $@ :代表『 “$1” “$2” “$3” “$4” 』之意,每个变量是独立的(用双引号括起来);
 $* :代表『 “$1c$2c$3c$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."
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	<==第二个参数

shift:造成参数变量号码偏移

#!/bin/bash
# Program:
#
Program shows the effect of shift function.
# History:
# 2009/02/17
VBird
First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"
shift
# 进行第一次『一个变量的 shift 』
echo "Total parameter number is ==> $#"
echo "Your whole parameter is==> '$@'"
shift 3 
# 进行第二次『三个变量的 shift 』
echo "Total parameter number is ==> $#"
echo "Your whole parameter is==> '$@'"

执行成果如下:

[dmtsai@study bin]$ sh shift_paras.sh one two three four five six <==给予六个参数
Total parameter number is ==> 6
Your whole parameter is ==> 'one two three four five six'
Total parameter number is ==> 5
Your whole parameter is ==> 'two three four five six'
<==第一次偏移,看底下发现第一个 one 不见了
Total parameter number is ==> 2
Your whole parameter is ==> 'five six'
<==最原始的参数变量情况
<==第二次偏移掉三个,two three four 不见了

猜你喜欢

转载自blog.csdn.net/qq_52835624/article/details/119173034