Bash:意外标记“then”附近的语法错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21671343/
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:31:40  来源:igfitidea点击:

Bash: Syntax error near unexpected token `then'

linuxbashif-statement

提问by user3291870

the error is at line 21...

错误在第 21 行...

if [ $weight1 -gt $weight2 ];
    then echo "Weight 2 should be greater than Weight 1."
else
    if [ $weight1 -ge 20 ] && [ $weight1 -le 39 ];
        then echo "Weight 1 is bike."
    else 
        echo "Weight 1 is either bicycle, car, van or lorry."
    fi
fi

回答by Малъ Скрылевъ

I done\'t see the issue, on my tests thenkeyword is worked for your case, anyway some noted on your code:

我没有看到这个问题,我的测试then关键字适用于您的情况,无论如何,您的代码中有一些注释:

  1. Put thenon the line of ifoperator:

    if [ $weight1 -ge 20 ] && [ $weight1 -le 39 ]; then
    
  2. Enclose your variables into quotes:

    if [ "$weight1" -ge 20 ] && [ "$weight1" -le 39 ]; then
    
  3. I recommend to use -akey, instead to two calls to [app:

    if [ "$weight1" -ge 20 -a "$weight1" -le 39 ]; then
    
  1. 放在运算符then的行上if

    if [ $weight1 -ge 20 ] && [ $weight1 -le 39 ]; then
    
  2. 将变量括在引号中:

    if [ "$weight1" -ge 20 ] && [ "$weight1" -le 39 ]; then
    
  3. 我建议使用-a密钥,而不是两次调用[应用程序:

    if [ "$weight1" -ge 20 -a "$weight1" -le 39 ]; then
    

NOTE:The error Syntax error near unexpected token 'then'can rise up mostly in a few cases:

注意:Syntax error near unexpected token 'then'在少数情况下,错误可能会增加:

  1. When you specify thenkeyword outside of ifcase:

    weight1=21
        then echo "Weight 1 is bike."
    else
        echo "Weight 1 is either bicycle, car, van or lorry."
    fi
    
  2. when youve specified thentwice:

    if [ "$weight1" -ge 20 -a "$weight1" -le 39 ]; then
    then echo "Weight 1 is bike."
    
  3. when you've put thento improper place, for example, after the elseoperator:

    else
    then
        echo "Weight 1 is either bicycle, car, van or lorry."
    fi
    
  1. 当您thenif大小写之外指定关键字时:

    weight1=21
        then echo "Weight 1 is bike."
    else
        echo "Weight 1 is either bicycle, car, van or lorry."
    fi
    
  2. 当您指定then两次时:

    if [ "$weight1" -ge 20 -a "$weight1" -le 39 ]; then
    then echo "Weight 1 is bike."
    
  3. 当你放在then不合适的地方时,例如,在else操作员之后:

    else
    then
        echo "Weight 1 is either bicycle, car, van or lorry."
    fi
    

回答by MLSC

just

只是

chmod +x test.sh

first line: add #!/bin/bash

第一行:添加 #!/bin/bash

then do:

然后做:

./test.sh

It is working whithout problem

它可以正常工作