【问题标题】:Bash if or statement, command not foundBash if 或语句,找不到命令
【发布时间】:2017-09-21 22:21:22
【问题描述】:

我对这行 shell 脚本有疑问:

if [ "$(lsb_release -r -s)" == "16.04" ] || [ "$(lsb_release -r -s)" == "17.04" ]; then

我在运行脚本时得到“[: command not found”。我不明白为什么。

+ '[' -f /etc/debian_version ']'
++ lsb_release -r -s
+ '[' 17.04 == 16.04 ']'
++ lsb_release -r -s
+ ' [' 17.04 == 17.04 ']'
./mhn/scripts/install_mongo.sh: line 8:  [: command not found

如果在 17.04 上运行,我只会收到错误,而不是 16.04。如果我切换语句并首先检查 17.04,它将在 16.04 中断,而不是 17.04。声明的后半部分有些内容是错误的。

https://github.com/ngatilio/mhn/blob/2e992934a350e0367a214dc86cc63e7ecd5d59ef/scripts/install_mongo.sh

【问题讨论】:

  • 在您的问题中添加操作系统(Ubuntu?)和 bash 版本。
  • 如果您将该行复制粘贴到一个新脚本中,然后单独运行该脚本,您是否仍然会遇到同样的错误?
  • @thatotherguy 如果只是 if 语句,它就可以正常工作。但在完整的脚本中,它位于第 8 行,bash 告诉我“第 8 行:[: command not found”
  • @d1str0 您能否包含运行脚本的完整、未缩写的输出,包括您用来运行它的命令?它有set -x,所以它应该打印大量有用的输出
  • @thatotherguy 更新

标签: bash shell ubuntu


【解决方案1】:

这是你的问题:

+ ' [' 17.04 == 17.04 ']'

您在最后一个[ 之前似乎有某种时髦的空格字符。删除并重新输入它以将其变成常规的 ascii 空间。

当您在此处复制粘贴该行时,或者通过非原始 github 视图查看它时,它会被转换为常规空间,因此它不会出现在您的帖子中。这也是为什么它在复制粘贴到另一个文件时可以正常工作的原因。

这是从 github 下载(而非复制粘贴)的文件的 ShellCheck:

$ shellcheck install_mongo.sh

In install_mongo.sh line 8:
    if [ "$(lsb_release -r -s)" == "16.04" ] || [ "$(lsb_release -r -s)" == "17.04" ]; then
                                               ^-- SC1018: This is a unicode non-breaking space. Delete and retype it.

【讨论】:

  • @d1str0:这说明了问题:cat -A install_mongo.sh | sed -n 8p
  • 哇!那是一个皮塔饼。此外,shellcheck 似乎超级酷。非常感谢!
【解决方案2】:

试试这个:

if [ "$(lsb_release -r -s)" == "16.04" -o "$(lsb_release -r -s)" == "17.04" ]; then

【讨论】:

  • 感谢您的回答,但不幸的是,这并不能解决我的问题。另一个答案完全解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
  • 2011-12-12
  • 2013-09-18
  • 2016-05-27
  • 1970-01-01
  • 2016-09-02
相关资源
最近更新 更多