【问题标题】:Bash - syntax error near unexpected token `fi'Bash - 意外标记“fi”附近的语法错误
【发布时间】:2015-03-21 17:16:30
【问题描述】:
#!/usr/bin/env bash

if [[ $# -eq '0' ]]
then
    var=command

    if [[ ${var} -eq '0' ]]
    then
        do something
    else
        do something else
    fi
fi

if [[ $# -eq '1' ]]
    usage;
fi

if [[ $# -eq '2' ]]
    if [[ "$1" != "-r" ]]
    then
        usage;
    fi
    if [[ "$2" =~ some_pattern ]]
    then
        do something
    else
        echo "Pattern is in an improper format. Please enter it as: correct_pattern, and try again"
        exit 1
    fi
    usage="Usage: meta_script.sh -r correct_pattern
    -r for reset is used to manually pass a parameter instead of using the default"
exit 1
fi

当我运行这个脚本时,这是我得到的错误:

./meta_script.sh: line 31: syntax error near unexpected token `fi'
./meta_script.sh: line 31: `fi'

在我检查参数数量是否等于 1 的第一个 if 语句中,我放了一个 then,但我得到了与上面相同的错误,除了 then 而不是 @ 987654327@。就好像无论我在哪里放什么,我都会收到这些错误,当我删除它们以尝试修复它时,我又会收到一堆类似的错误。请帮我纠正这个脚本。谢谢!

【问题讨论】:

  • 您错过了thenif [[ $# -eq '1' ]]if [[ $# -eq '2' ]]。试试shellcheck.net
  • 谢谢!我会试试的,让你知道。如果可行,请将其作为答案,我会接受。再次感谢!
  • @EtanReisner:成功了!我现在遇到另一个错误,但本质上,它不一样并且有效。谢谢!你能帮我解决这个错误吗?当我给它错误数量的参数时会发生这种情况。而不是去使用,它只是退出。可能会发生什么?我将在这里修改代码以反映“工作”代码,希望您能帮助我。谢谢!
  • @EtanReisner:没关系。我让它工作了!再次感谢您的帮助:)

标签: bash if-statement parameters parameter-passing argument-passing


【解决方案1】:

关于分段:

if [[ $# -eq '2' ]]
    if [[ "$1" != "-r" ]]
    then

您缺少第一个 if 语句的 then。把它放进去应该会让你克服那个错误:

if [[ $# -eq 2 ]] ; then
    if [[ "$1" != "-r" ]] ; then

你会看到我把 then 放在了同一行,因为这是一个很好的习惯,意识到 ifthen 总是一起出现(与 whiledo 相同) )。它还允许您在任何给定终端上查看更多“有用”代码行:-)

我还去掉了2 周围的无用引号,因为$# 总是返回一个数值。我建议坚持只对字符串使用引号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 2018-12-18
    相关资源
    最近更新 更多