【问题标题】:How do I get a variable into a $(shell) command in a makefile?如何将变量放入 makefile 中的 $(shell) 命令中?
【发布时间】:2020-07-02 19:26:15
【问题描述】:
❯ make --version
GNU Make 3.81
❯ bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)

如何将变量从 for 循环内部传递给 $(shell)?我可以访问 $(shell) 之外的 var,但我不知道如何将其传递:

A_LIST:= one two

.PHONY: loop
loop:
    @for iii in $(A_LIST) ; do \
        echo inside recipe loop with sh command: $$iii ; \
        export SAVED_OUTPUT=$(shell echo $$iii) ; \
        echo $$SAVED_OUTPUT ; \
    done

这是我得到的输出:

inside recipe loop with sh command: one
<blank line here>
inside recipe loop with sh command: two
<blank line here>

循环中的最后一行 echo $$SAVED_OUTPUT 应该输出 onetwo,因为它会回显 var 并将其存储在另一个 var 中。但它是一个空白行。我怀疑这是因为它正在寻找一个 env var $iii 但这不存在 - 那么如何将 iii 的值传递到 shell 中?

这是我不喜欢的一种不好的做法。我不想为了访问这样的变量而编写本地文件:

.PHONY: loop
loop:
    @for iii in $(A_LIST) ; do \
        echo inside recipe loop with sh command: $$iii ; \
        echo $$iii > scratch ; \
        export SAVED_OUTPUT=$(shell echo $$(cat scratch)) ; \
        echo $$SAVED_OUTPUT ; \
    done

【问题讨论】:

  • 请添加您想要的输出(无描述)。
  • 添加了所需的输出
  • 没有必要在这里使用 make $(shell) 函数在已经被 shell 执行的东西中......
  • export 将变量导出到子进程。无法在父进程中设置变量。
  • 我需要存储 shell 命令的输出以用于另一个 shell 命令并将它们链接在一起

标签: bash makefile gnu-make


【解决方案1】:

for 循环已经由 shell 执行 - 在这种情况下,也没有理由将 $(shell ...) 也带入其中。只需使用普通的$() shell 命令替换语法(将$ 加倍以使 make 快乐,就像变量名一样):

A_LIST:= one two

.PHONY: loop
loop:
    @for iii in $(A_LIST) ; do \
        echo "inside recipe loop with sh command: $$iii" ; \
        SAVED_OUTPUT="$$(somecommand "$$iii")" ; \
        echo "$$SAVED_OUTPUT" ; \
    done

【讨论】:

  • 我需要将 iii 的值用于 shell 命令并将该 shell 命令的输出存储在 SAVED_OUTPUT 中
  • @red888 所以使用普通的 shell 表示法(使用转义 $ 以防止 make 评估):SAVED_OUTPUT="$$(somecommand "$$iii")"
  • 哇,这确实有效。我打算删除我的问题,因为现在我看到它首先要做的是一件丑陋的事情,但很高兴知道它是可能的。您可以将其添加到您的答案中吗?
猜你喜欢
  • 1970-01-01
  • 2018-12-21
  • 2011-12-19
  • 2011-06-20
  • 2013-06-28
  • 2015-11-17
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多