【问题标题】:bash: why is this command running when the condition hasn't been met? [duplicate]bash:为什么在不满足条件时运行此命令? [复制]
【发布时间】:2017-09-30 02:43:15
【问题描述】:

我正在尝试整合我的点文件,因此我只有一套用于本地 OSX 机器和 Linux 服务器。我有这个条件语句,但 $(brew --prefix) 正在 Linux 机器上运行,即使该块不应该运行......

SYSTEM=`uname -a | cut -d" " -f1`
# These things are system specific
if [ $SYSTEM=="Darwin" ]; then
    if [ -f $(brew --prefix)/etc/bash_completion ]; then
        . $(brew --prefix)/etc/bash_completion
    fi

    for file in ~/.completion/* ; do
      if [ -f "$file" ] ; then
        . "$file"
      fi
    done

elif [ $SYSTEM=="Linux" ]; then
    alias upgrade='sudo apt-get update && sudo apt-get upgrade'

    # save the IP address in case I need it later
    export IP_ADDRESS=`ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'`
fi

如果我在 linux 机器上回显 $SYSTEM 变量,它说它是 Linux,但在 brew --prefix 命令上获取 bashrc 失败。

无论如何它都会评估该变量吗?有什么办法可以让它工作吗?

【问题讨论】:

标签: bash


【解决方案1】:

== 周围需要空格:

if [ $SYSTEM == "Darwin" ]

否则 bash 的行为就像你写的一样:

if [ "some-non-empty-string" ]

总是true,而不是:

if [ "" ]

总是false

【讨论】:

  • 另外,单个等号 (=) 在 [ ] 中是标准的。 bash 允许 == 作为同义词,但它不一定在其他 shell 中工作。双引号变量引用(例如if [ "$SYSTEM" = "Darwin" ])总是一个好习惯
猜你喜欢
  • 1970-01-01
  • 2019-06-10
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 2012-06-20
  • 2013-07-08
相关资源
最近更新 更多