Use the result of a shell command in a conditional in a makefile

白昼怎懂夜的黑 提交于 2019-12-29 09:56:27

问题


I am trying to execute a command in a conditional in a makefile.

I got it working in a shell:

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

but if I try it in a makefile, "$(ls -A mydir)" expands to nothing whatever if asdf is empty or not:

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

The ls command does not expand as I expect:

$ 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

How do I make the command work inside the conditional?


回答1:


I have little experience in writing makefiles. However I think you must use two dollar signs in your recipe:

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

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

if you want a dollar sign to appear in your recipe, you must double it (‘$$’).

This is an example of output after I changed your makefile and added $$(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


来源:https://stackoverflow.com/questions/28090490/use-the-result-of-a-shell-command-in-a-conditional-in-a-makefile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!