一、向脚本中传递位置参数
向脚本中传递参数的数目理论上可以无数多,但是只有前9个能被访问,使用shift可以改变此限制
$0 | $1 | $2 | $3 | $4 | $5 | $6 | $7 | $8 | $9 |
脚本名字 | first | second | third | fourth | fifth | sixth | seventh | eighth | ninth |
1 $ vim param 2 3 #!/bin/sh 4 echo "This is the script name : $0" 5 echo "This is the first param : $1" 6 echo "This is the second param : $2" 7 echo "This is the third param : $3" 8 echo "This is the fourth param : $4" 9 echo "This is the fifth param : $5" 10 echo "This is the sixth param : $6" 11 echo "This is the seventh param : $7" 12 echo "This is the eighth param : $8" 13 echo "This is the ninth param : $9"
$ chmod u+x param
$ ./param Did You See The Full Moon
This is the script name : Did This is the first param : You This is the second param : See This is the third param : The This is the fourth param : Full This is the fifth param : Moon This is the sixth param :
This is the seventh param :
This is the eighth param : This is the ninth param :
二、向系统命令中传递参数
1 $ vim findfile 2 #!/bin/sh 3 # findfile 4 find / -name $1 -print #find $1 in / 5 6 $ chmod u+x findfile 7 $ findfile passwd 8 /etc/passwd 9 /etc/uucp/passwd 10 /usr/bin/passwd
三、特定变量参数
$# | 传递到脚本的参数个数 |
$* | 以一个单字符串显示所有向脚本传递的参数 |
$$ | 脚本运行的当前进程ID号 |
$! | 后台运行的最后一个进程的ID号 |
$@ | 与$#相同,但是 使用时加双引号 |
$- | 显示shell使用的当前选项 |
$? | 显示最后命令的退出状态 |
$ vim param #!/bin/sh echo "This is the script name : $0" echo "This is the first param : $1" echo "This is the second param : $2" echo "This is the third param : $3" echo "This is the fourth param : $4" echo "This is the fifth param : $5" echo "This is the sixth param : $6" echo "This is the seventh param : $7" echo "This is the eighth param : $8" echo "This is the ninth param : $9" echo "The number of arguments passed : $#" echo "show all arguments : $*" echo "did my script go with any errors : $?" $ chmod u+x param $ ./param Did You See The Full Moon This is the script name : Did This is the first param : You This is the second param : See This is the third param : The This is the fourth param : Full This is the fifth param : Moon This is the sixth param : This is the seventh param : This is the eighth param : This is the ninth param The number of arguments passed : 6 show all arguments : Did You See The Full Moon did my script go with any errors : 0