如何确保用户输入有效的开关案例选项?

时间:2018-05-06 02:15:08

标签: linux shell switch-statement sh

我试图弄清楚如何修复此代码...

echo -n "Enter you complaint : ";
read complaint;


if [[ -z $complaint ]] || [[ $complaint != 'FIRE' ]] || [[ $complaint != 'INTOXICATION' ]] || [[ $complaint != "INJURY" ]] || [[ $complaint != "BREAKAGE" ]] ;then
    echo "Not a good option";
    exit 1;
fi


case $complaint in
    FIRE)  = $complaint=$(echo "FIRE");;
    INTOXICATION) = $complaint=$(echo "INTOXICATION");;
    INJURY) = $complaint=$(echo "INJURY");;
    BREAKAGE) = $complaint=$(echo "BREAKAGE");;
esac

有可能知道: 为什么即使输入有效的东西也总是输入if?

1 个答案:

答案 0 :(得分:2)

if中的条件错误,应该是:

if [[ -z $complaint ]] || [[ ( $complaint != 'FIRE' && $complaint != 'INTOXICATION' && $complaint != "BRIS" && $complaint != "BOBO" ) ]] ;then

也就是说,如果if$complaintnull),或者它与任何有效选项都不匹配,您希望进入-z $complaint内部,所以它必须同时与所有这些不同,因此&&而不是||

或者,您也可以在case...esac块中使用默认条件:

case $complaint in
    FIRE)  = $complaint=$(echo "FIRE");;
    INTOXICATION) = $complaint=$(echo "INTOXICATION");;
    INJURY) = $complaint=$(echo "INJURY");;
    BREAKAGE) = $complaint=$(echo "BREAKAGE");;
    *) echo "Not a good option"; exit 1;;
esac