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

时间:2015-01-22 19:10:59

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

#!/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代替fi。它几乎就好像无论我放在哪里和哪里,我都会遇到这些错误,当我删除它们以尝试修复它时,我会得到另一堆类似的错误。请帮我纠正这个脚本。谢谢!

1 个答案:

答案 0 :(得分:0)

关于细分:

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

您错过了第一个then语句的if。把它放进去会让你超越这个错误:

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

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

我已经摆脱do周围无用的引号,因为2总是返回一个数值。我建议坚持只为字符串使用引号。

相关问题