SHELL的变量类型
环境变量
本地变量
位置变量
$1,$2...
shift,轮换
特殊变量
$#:统计参数的个数
shift
下面我们就以脚本实例来说明下位置变量的运用
如写一脚本,用户输入文件名作为参数,判定参数的个数并判定文件是否存在,并判定是否为普通文件、目录或其它
[root@station01 ~]# cat test13.sh #!/bin/bash # #FILES=/etc/rc.d/rc.sysinit if [ ! -e $1 ];then echo "No such file..." exit 24 fi if [ -f $1 ];then echo "Common file..." elif [ -d $1 ];then echo "Directory .." else echo "Unknown." fi
执行结果:
[root@station01 ~]# ./test13.sh /root/ Directory ..
如shift 用法
1)
[root@station01 ~]# cat shift.sh #!/bin/bash # echo $1 shift echo $1 shift echo $1 shift
执行结果
[root@station01 ~]# ./shift.sh a b c a b c
2)
[root@station01 ~]# cat shift.sh #!/bin/bash # echo $1 shift 2 echo $1 shift 2 echo $1 shift 2
执行结果
[root@station01 ~]# ./shift.sh a b c d e a c e
计算两数之和及之积,通过传参实现
[root@station01 ~]# cat cacl.sh #!/bin/bash # if [ $# -lt 2 ];then echo "Argument less than 2." fi echo "The sum is:$[$1+$2]" echo "The prod is :$[$1*$2]"
执行结果
[root@station01 ~]# ./cacl.sh 2 5 The sum is:7 The prod is :10
转载于:https://blog.51cto.com/yujiqing/1616311