Bash - 意外标记“fi”附近的语法错误

Bash - syntax error near unexpected token `fi'

#!/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 [[ "" != "-r" ]]
    then
        usage;
    fi
    if [[ "" =~ 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 而不是 fi。就好像无论我在什么地方放什么,我都会遇到这些错误,当我删除它们以尝试修复它时,我又遇到了一堆类似的错误。请帮我更正这个脚本。谢谢!

关于段:

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

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

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

你会看到我把 then 放在同一行,因为这是一个养成的好习惯,意识到 ifthen 总是在一起(相同如 whiledo)。它还允许您在任何给定终端上查看更多行 "useful" 代码:-)

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