【问题标题】:bash shell [[ operator failed with error: "conditional binary operator expected"bash shell [[ 运算符失败,出现错误:\"需要条件二元运算符\"
【发布时间】:2023-01-26 06:47:36
【问题描述】:

我在解析时在以下 bash shell 脚本的第一行中遇到错误。

  if [[ -v VAR_1 ]]; then
    VAR_2="$VAR_1/sub_folder"
  fi

这个脚本在我同事的 Bash shell Linux 机器上运行良好,但在我的 Macbook MacOS 上运行失败。

错误信息是

conditional binary operator expected

【问题讨论】:

    标签: bash shell


    【解决方案1】:

    事实证明,我的 MacOS 正在运行 zsh 而不是 bash。

    为了使此脚本与 bash 和 zsh shell 兼容,请改用以下内容,它符合 POSIX 标准并且在 zsh 和 bash 中都有效。

     if [ -v VAR_1 ]; then
        VAR_2="$VAR_1/sub_folder"
      fi
    

    或者

      if test -v VAR_1 ; then
    

    原因:

    [[ 命令是 Bourne Again Shell (bash) 的一项功能。它是 [ 命令的扩展版本,也用于 bash 和其他 shell 中的条件测试。

    在 Zsh 中,[[ 是一个 shell 关键字,但默认情况下它的工作方式与 bash 不同。默认情况下,它在 Zsh 中用于不同的目的,这就是为什么我收到错误“预期的条件二元运算符”。

    或者,

    我也可以使用 emulate sh 命令告诉 Zsh 模拟 Bourne shell (sh) 的行为,包括 bash。这允许在 Zsh 中使用 [[ 和其他特定于 bash 的命令和语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      相关资源
      最近更新 更多