bash shell 脚本中意外标记“then”附近的语法错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22140238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:47:07  来源:igfitidea点击:

Syntax error near unexpected token 'then' in shell script

bashshell

提问by Niraj Dave

I am new to shell scripting and this is my first shell script.i am getting this error and stuck in it.following is the simple code for it:

我是 shell 脚本的新手,这是我的第一个 shell 脚本。我收到此错误并陷入其中。以下是它的简单代码:

#!/bin/sh
yes=y;
no=n;
echo "Do you want to enter batch order id manually? (y/n) "
read answer
if [ $answer -eq $yes ]; then
    echo "Please Enter Batch Order Id."
elif[ $answer -eq $no ]; then
    echo "Copying all batch orders."
else
    echo"please enter correct input."
fi

回答by John1024

The script needs a couple minor changes:

该脚本需要一些小的更改:

#!/bin/sh
yes=y;
no=n;
echo "Do you want to enter batch order id manually? (y/n) "
read answer
if [ "$answer" = $yes ]; then
    echo "Please Enter Batch Order Id."
elif [ "$answer" = $no ]; then
    echo "Copying all batch orders."
else
    echo "please enter correct input."
fi

A space is needed after elifand before [ $answer -eq $no ]. The tests make string comparisons, not numeric comparisons. So, =is needed in place of -eq. So that the script works even if the user enters nothing, $answeris placed inside double-quotes in the tests. Also, a space is required between echoand "please enter correct input.".

elif前后需要一个空格[ $answer -eq $no ]。测试进行字符串比较,而不是数字比较。所以,=需要代替-eq. 即使用户什么都不输入,脚本也能工作$answer,在测试中放在双引号内。此外,echo和之间需要一个空格"please enter correct input."