Linux shel编程之命令行参数处理

来源:互联网 发布:淘宝上下架在那里 编辑:程序博客网 时间:2024/06/15 23:30

在运行脚本程序中,用户可以通过命令行参数将参数传递给脚本程序:

# ./test 10 a
通过一些特殊的变量:位置参数,可以在脚本中取得命令行参数。其中,$0为程序名称,$1为第一个参数,$2为第二个参数,依此类推 $9为第九个参数。
# cat test.sh #!/bin/bashecho "shell name is $0"echo "first args is $1"echo "second args is $2"# ./test.sh shell name is ./test.shfirst args is second args is # ./test.sh  1 2 shell name is ./test.shfirst args is 1second args is 2
在第一次运行./test.sh时,没有传入参数,可以看出$1,$2值为空。
每个参数都是通过空格分隔的,如果输入的参数中包含空格,要用引号(" "或' ‘)包起来。
# ./test.sh  "hello world!" 2shell name is ./test.shfirst args is hello world!second args is 2
如果命令行参数多于9个,如果想取得后面的参数,使用${10},${11}..,$(n)取得。虽然我们可以通过$0确定程序的名称,但是$0中包括程序完整的路径。
# cat test.sh#!/bin/bashecho "shell name is $0"# ./test.shshell name is ./test.sh# /home/jie/code/shellcode/test.sh shell name is /home/jie/code/shellcode/test.sh
有时候我们仅仅想获得程序的名称(不包括具体路径),可以使用basename命令取得程序名称(name=`basename $0`)。
# cat test.sh#!/bin/bashname=`basename $0`echo "shell name is $name"# ./test.shshell name is test.sh# /home/jie/code/shellcode/test.sh shell name is test.sh
在使用shell脚本中的命令行参数之前,必须对参数进行检查,以保证命令行参数中确实包含我们想要的数据。
$ cat test.sh#!/bin/bashif [ -n "$1" ]then   echo "hello $1!"else   echo "Please input a name!"fi$ ./test.sh mikehello mike!$ ./test.sh Please input a name!
2、特殊的参数变量
在bash shell中有一些特殊的参数变量,用于跟踪命令行参数。

(1)命令行参数个数
变量$#记录了脚本启动时的命令行参数的个数。

# cat test.sh#!/bin/bashecho "the count of args is : $#"# ./test.sh 1 2 3 4 the count of args is : 4# ./test.sh 1 2 3 4 5 6 "hello"the count of args is : 7
(2)命令行所有参数
变量$*和$@包含了全部命令行参数(不包括程序名称$0),变量$*将命令行的所有参数作为一个整体处理。而$@将所有参数当作同一个字符串的多个单词处理,允许对其中的值进行迭代。
# cat test.sh #!/bin/bashecho "Using the \$* method:$*"echo "Using the \$@ method:$@"# ./test.sh 1 2 3 Using the $* method:1 2 3Using the $@ method:1 2 3
下面这个例子展示了$*和$@的不同之处
# cat test.sh#!/bin/bashcount=1for param in "$*"do    echo "\$* Parameter #$count = $param"    count=$[$count+1]donecount=1for param in "$@"do    echo "\$@ Parameter #$count = $param"    count=$[$count+1]done# ./test.sh 1 2 3$* Parameter #1 = 1 2 3$@ Parameter #1 = 1$@ Parameter #2 = 2$@ Parameter #3 = 3
3、命令行参数移位
bash shell提供shift命令帮助操作命令行参数,shift命令可以改变命令行参数的相对位置,默认将每个参数左移一个位置,$3的值移给$2,$2的值移给$1,$1的值被丢弃。
注意:$0的值和位置不受shift命令影响。$1移掉后,该参数值就丢失了,不能恢复。
# cat test.sh#!/bin/bashcount=1while [ -n "$1" ]do  echo "Parameter #$count = $1"  count=$[$count+1]  shiftdoneecho "\$#=$#"echo "\$*=$*"echo "\$@=$@"echo "\$1=$1"# ./test.sh 1 2 3 Parameter #1 = 1Parameter #2 = 2Parameter #3 = 3$#=0$*=$@=$1=
shift命令可以带一个参数实现多位移变化,命令行参数向左多个位置。
# cat test.sh#!/bin/bashecho "The origin parameters are:$*"shift 2echo "after shift 2 the parameters are:$*"# ./test.sh 1 2 3 4 5 The origin parameters are:1 2 3 4 5after shift 2 the parameters are:3 4 5 

0 0