【问题标题】:Why am I getting a "line 10: syntax error near unexpected token `fi'" error in bash script?为什么我在 bash 脚本中收到“第 10 行:意外标记‘fi’附近的语法错误”错误?
【发布时间】:2021-10-04 13:34:07
【问题描述】:

我正在尝试在 bash 中创建一个函数:

check_for_file()
{
if [ $1 = '' ]; then
        local testing_file = myproject
elif
        local testing_file = $1
fi

if [ -d testing_file ]; then
        echo "Directory name already exists"
        exit
elif
        mkdir -p testing_file/{archive,backups,docs/html,docs/txt,assets,database,src/sh,src/c}
fi
return
}

但是当我运行它时,我得到以下输出: ./mkproj.sh:第 10 行:意外标记附近的语法错误 fi' ./mkproj.sh: line 10: fi'

你知道我做错了什么吗?谢谢!

【问题讨论】:

  • elif 需要附加条件。你只想要else
  • 顺便说一句,它是mkdir -p "$testing_file"/...。您当前没有将变量扩展为供 mkdir 使用的值。
  • 正如 chepner 所说,elif 中的条件缺失,但是您还需要一个 then。请参阅 bash 手册页,其中将 if 语句描述为:if list; then list; [ elif list; then list; ] ... [ else list; ] fi

标签: bash unix conditional-statements


【解决方案1】:

elif 期望另一个命令进行测试。抛开格式不谈,local testing_file = $1 被视为该条件,但随后会在预期的 then 关键字之前看到关键字 fi

改用else

if [ $1 = '' ]; then
        local testing_file=myproject
else
        local testing_file=$1
fi

(也请注意,您不能在作业中的 = 周围放置空格。

【讨论】:

    【解决方案2】:

    您应该在elif 语句之后使用then 但是你的说法也是错误的,因为elif需要一个命令来测试

    因此,在您的情况下,只需使用 else

    【讨论】:

      猜你喜欢
      • 2015-03-21
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      相关资源
      最近更新 更多