要想对脚本中的参数是否为空值使用[ -z "$var" ]判断即可;但是当一个shell脚本需要输入多个参数时,如果单单使用if判断代码会显得很长!
例如:if [-z "${vals[1]}" ] || [-z "${vals[2]}" ] || [-z "${vals[3]}" ] || [-z "${vals[4]}" ]; then
看4个参数就已经如此之长!
如果加入for循环判断就会简洁很多;例如for ((i=1;i<m;i++))doif [ -z "${vals[i]}" ]; then echo "The $i parameter are missing!"exit 1fidone
下面引用一个实例:
#!/bin/bashparamStr=""for s in $@do paramStr=$paramStr$sdoneecho $paramStr
#不输入参数是执行脚本将直接退出psLength=${#paramStr} [ $psLength == 0 ] && { echo "Parameters are missing!" ;exit 1; }
[ ";" == ${paramStr:psLength-1} ] && paramStr=${paramStr:0:psLength-1} echo $paramStr
#分别将参数值赋值给数组vals[i]arr=(${paramStr//,/ })vals=()i=1for ar in ${arr[@]}doindex=`expr index "$ar" =`vals[i]=${ar:index}i=$i+1done
#将数组个数加1赋值给mlet "m=${#vals[@]}+1"
#循环判断第i个参数是否为空,为空即退出for ((i=1;i<m;i++))doif [ ! -n "${vals[i]}" ]; then #这里还可以改为 if [ -z "${vals[i]}" ]; thenecho "The $i parameter are missing!"exit 1fidone