【问题标题】:Use the result of a shell command in a conditional in a makefile在 makefile 的条件中使用 shell 命令的结果
【发布时间】:2015-01-22 13:54:03
【问题描述】:

我正在尝试在 makefile 的条件中执行命令。

我让它在 shell 中工作:

if [ -z "$(ls -A mydir)" ]; then \
  echo "empty dir"; \
else \
  echo "non-empty dir"; \
fi

但如果我在 makefile 中尝试,"$(ls -A mydir)" 会扩展为空,无论asdf 是否为空:

all:
    if [ -z "$(ls -A mydir)" ]; then \
      echo "empty dir"; \
    else \
      echo "non-empty dir"; \
    fi

ls 命令没有像我预期的那样扩展:

$ mkdir mydir
$ make
if [ -z "" ]; then \
      echo "empty dir"; \
    else \
      echo "non-empty dir"; \
    fi
empty dir
$ touch mydir/myfile
$ make
if [ -z "" ]; then \
      echo "empty dir"; \
    else \
      echo "non-empty dir"; \
    fi
empty dir
$ ls -A mydir
myfile

如何使命令在条件内工作?

【问题讨论】:

    标签: shell makefile sh


    【解决方案1】:

    我几乎没有编写 makefile 的经验。但是我认为你必须在你的食谱中使用两个美元符号:

    all:
        if [ -z "$$(ls -A mydir)" ]; then \
    

    https://www.gnu.org/software/make/manual/make.html#Variables-in-Recipes:

    如果你想让一个美元符号出现在你的食谱中,你必须加倍 它('$$')。

    这是我更改您的 makefile 并添加 $$(ls -A mydir) 后的输出示例:

    $ ls mydir/
    1
    
    $ make
    if [ -z "$(ls -A mydir)" ]; then \
          echo "empty dir"; \
        else \
          echo "non-empty dir"; \
        fi
    non-empty dir
    
    $ rm mydir/1
    
    $ make
    if [ -z "$(ls -A mydir)" ]; then \
          echo "empty dir"; \
        else \
          echo "non-empty dir"; \
        fi
    empty dir
    

    【讨论】:

    • 当我看到它时,它是如此明显,我什至不得不问。谢谢。
    猜你喜欢
    • 2013-10-14
    • 2019-08-05
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 2013-05-09
    相关资源
    最近更新 更多