shell——位置变量参数_特定变量参数

位置变量参数

位置变量。如果要向一个脚本传递信息,可以使用位置参数完成此功能。参数相关数目传入脚本,此数目可以任意多,但只有前9个可以被访问,使用shift命令可以改变这个限制。

参数从第一个开始,在第9个结束;每个访问参数前要加$符号。第一个参数为0,表示预留保存实际脚本名字。无论脚本是否有参数,此值均可用。

例:

[hadoop@localhost d4]$ ./d4.sh
this is the script file name:./d4.sh
this is the script path file name:d4.sh
this is the 1st parameter :
this is the 2st parameter :
this is the 3st parameter :
this is the 4st parameter :
this is the 5st parameter :
this is the 6st parameter :
this is the 7st parameter :
this is the 8st parameter :
this is the 9st parameter :
[hadoop@localhost d4]$ ./d4.sh 1 2 3 4 5 6
this is the script file name:./d4.sh
this is the script path file name:d4.sh
this is the 1st parameter :1
this is the 2st parameter :2
this is the 3st parameter :3
this is the 4st parameter :4
this is the 5st parameter :5
this is the 6st parameter :6
this is the 7st parameter :
this is the 8st parameter :
this is the 9st parameter :
[hadoop@localhost d4]$ cat d4.sh
#!/bin/sh
echo "this is the script file name:$0"
echo "this is the script path file name:`basename $0`"
echo "this is the 1st parameter :$1"
echo "this is the 2st parameter :$2"
echo "this is the 3st parameter :$3"
echo "this is the 4st parameter :$4"
echo "this is the 5st parameter :$5"
echo "this is the 6st parameter :$6"
echo "this is the 7st parameter :$7"
echo "this is the 8st parameter :$8"
echo "this is the 9st parameter :$9"

这里只传递6个参数,7、8、9参数为空。注意,第一个参数表示脚本名,当从脚本中处置错误信息时,此参数有很大作用。

注意$0返回当前目录路径如果只返回脚本名,可以用basename $0,刚好得到脚本名字

basename file: 返回不包含路径的文件名比如: basename /bin/dd将返回dd。
dirname file: 返回文件所在路径比如:dirname /bin/dd将返回/bin。

----------------------------------------------------------------

向系统命令传递参数

可以在脚本中向系统命令传递参数。下面的例子中,find在命令里,使用$1参数指定查找文件名。

[hadoop@localhost d4]$ cat d5.sh
#!/bin/sh
find . -name $1 -print
[hadoop@localhost d4]$ ./d5.sh *05*
./d0505

特定变量参数

共有 7个特定变量,

$# 传递到脚本的参数个数

$* 所有命令行参数,以一个单字符串显示所有向脚本传递的参数。与位置变量不同,此选项参数可超过9个

$ 脚本运行的当前进程I D号

$! 后台运行的最后一个进程的进程ID号

$@ 与$*相同,但是使用时加引号,并在引号中返回每个参数

$- 显示shell使用的当前选项,与set命令功能相同

$? 显示最后命令的退出状态。 0表示没有错误,其他任何值表明有错误。

例:

[hadoop@localhost d4]$ cat d66.sh
#!/bin/sh
echo "this is the script file name:$0"
echo "this is the 1st parameter :$1"
echo "this is the 2st parameter :$#"
echo "this is the 2ffst parameter :$*"
echo "this is the 3st parameter :$"
echo "this is the 4st parameter :$@"
echo "this is the 5st parameter :$?"
[hadoop@localhost d4]$ sh d66.sh hj kl
this is the script file name:d66.sh
this is the 1st parameter :hj
this is the 2st parameter :2
this is the 2ffst parameter :hj kl
this is the 3st parameter :91251
this is the 4st parameter :hj kl
this is the 5st parameter :0

最后的退出状态

注意,$?返回0。可以在任何命令或脚本中返回此变量以获得返回信息。

返回0意味着成功,1为出现错误。

[hadoop@localhost d4]$ cp aa bb
cp: cannot stat 鈇a? No such file or directory
[hadoop@localhost d4]$ echo $?
1
[hadoop@localhost d4]$ cp 22 bb22
[hadoop@localhost d4]$ echo $?
0

2022-9-15

举报
评论 0