Bash:if中检查参数的多个条件

时间:2016-03-03 13:51:33

标签: bash shell unix

因此,要运行我的脚本,我使用如下参数:

./script 789

该参数用于更改文件或目录的权限,我想检查每个数字是否在0到7之间,所以我尝试的是接下来的事情:

 if [[ ${1:0:1} -ge 0 && ${1:0:1} -le 7 ]] && [[ ${1:1:1} -ge 0 && ${1:1:1} -le 7]] && [[ ${1:2:1} -ge 0 && ${1:2:1} -le 7]]
 then {go ahead with the code}
 else 
     echo "Error: each digit in the parameter must be between 0 and 7"
 fi

如果确实如此,那么请继续使用该脚本,否则会显示错误消息,但它似乎无法正常工作。

2 个答案:

答案 0 :(得分:2)

您希望将参数与正则表达式[0-7]{3}[[ "$1" =~ [0-7]{3} ]] || { echo 'invalid parameter' >&2; exit 1; } 匹配。在bash中,你可以这样做:

echo "$1" | grep -Eq '[0-7]{3}' || { echo err message >&2; exit 1; }

或者:

Playback.PlaybackSettings.ContinueOnError = True;

答案 1 :(得分:-1)

这可能是另一种方式

#!/bin/bash

#Stored input parameter 1 in a variable
perm="$1"

#Checking if inserted parameter is empty, in that case the script will show a help
if [ -z "${perm}" ];then
        echo "Usage: $0 <permission>"
        echo "I.e.: $0 777"
        exit
else
        #if the parameter is not empy, check if each digit is between 0-7
        check=`echo $perm| grep [0-7][0-7][0-7]`
        #if the result of command is empty that means that the input parameter contains at least one digit that's differs from 0-7
        if [ -z "${check}" ];then
                echo "Error: each digit in the parameter must be between 0 and 7"
        fi
fi

这是输出

[shell] ➤ ./test9.ksh 999
Error: each digit in the parameter must be between 0 and 7

[shell] ➤ ./test9.ksh 789
Error: each digit in the parameter must be between 0 and 7

[shell] ➤ ./test9.ksh 779
Error: each digit in the parameter must be between 0 and 7

[shell] ➤ ./test9.ksh 777