意外标记'case'附近的语法错误

时间:2018-10-30 18:01:44

标签: bash shell

这个问题可能之前曾被问过,但是我不明白这段代码有什么问题。因此此代码旨在在用户运行此代码时显示回复变量的菜单列表,而无需用户输入

#!/bin/bash
again='y'
while [ $again == 'y' ] || [ $again == 'Y' ];
do
 clear
 select menu in "Food1" "Food2" "Food3";
 case $REPLY in
 1) echo -n "Amount of plate =";
 read sum
 let pay=sum*1500;
 ;;
 2) echo -n "Amount of food =";
 read sum
 let pay=sum*2000;
 ;;
 3) exit 0
 ;;
 *) echo "Sorry, its unavailable"
 ;;
 esac
do
echo "Amount of pay = Rp. $pay"
echo "THX"
echo 
echo -n "Count again (y/t) :";
read again;
 #to validate input
 while [ $again != 'y' ] && [ $again != 'Y' ] && [ $again != 't' ] && [ $again != 'T' ];
 do
 echo "Ops, input with (y/Y/t/Y)";
 echo -n "Count again (y/t) :";
 read again;
 done
done

然后我得到这个错误

./script.sh: line 7: syntax error near unexpected token `case'
./script.sh: line 7: ` case $REPLY in'

1 个答案:

答案 0 :(得分:2)

c.f。 https://www.shellcheck.net/,它将为您检查bash语法。

Line 6:
 select menu in "Food1" "Food2" "Food3";
 ^-- SC1073: Couldn't parse this select loop. Fix to allow more checks.

Line 7:
 case $REPLY in
 ^-- SC1058: Expected 'do'.
 ^-- SC1072: Expected 'do'. Fix any mentioned problems and try again.

shellcheck是您的朋友。 :)

select menu in "Food1" "Food2" "Food3"
do : your logic here, AFTER the do
done

还有另一件事可以简化您的代码-无需检查所有情况的大小,只需对诸如此类的简单事情进行强制操作即可。

$ declare -l foo
$ foo=BAR
$ echo $foo
bar

因此,如果您再次使用$

declare -l again=y
while [[ y == "$again" ]]
do : ...

您永远不需要检查Y,因为它将是y。同样,在底部-

read again
until [[ "$again" =~ [yt] ]]
do printf "Y or T only please. Continue? [Y/t] "
   read again
done