如何在Makefile目标中使用Bash语法?

Fra*_*ank 194 bash shell makefile

我经常发现Bash语法非常有用,例如像diff <(sort file1) <(sort file2).中的进程替换.

是否可以在Makefile中使用此类Bash命令?我在考虑这样的事情:

file-differences:
    diff <(sort file1) <(sort file2) > $@
Run Code Online (Sandbox Code Playgroud)

在我的GNU Make 3.80中,这会产生错误,因为它使用shell而不是bash执行命令.

der*_*ert 353

从GNU Make文档中,

5.3.1 Choosing the Shell
------------------------

The program used as the shell is taken from the variable `SHELL'.  If
this variable is not set in your makefile, the program `/bin/sh' is
used as the shell.
Run Code Online (Sandbox Code Playgroud)

所以放在SHELL := /bin/bash你的makefile的顶部,你应该很高兴.

BTW:您也可以为一个目标执行此操作,至少对于GNU Make.每个目标都可以有自己的变量赋值,如下所示:

all: a b

a:
    @echo "a is $$0"

b: SHELL:=/bin/bash   # HERE: this is setting the shell for b only
b:
    @echo "b is $$0"
Run Code Online (Sandbox Code Playgroud)

那打印:

a is /bin/sh
b is /bin/bash
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅文档中的"特定于目标的变量值".该行可以在Makefile中的任何位置,它不必紧接在目标之前.

  • 500赏金等待`man`的报价.谈论时间.:P (36认同)
  • @inLoveWithPython嗯,`info`,实际上,但是,我猜它确实帮了安迪.我知道我有这样的日子...... (3认同)
  • 如果有疑问,@ derobert的字面意思是:`SHELL =/bin/bash`作为Makefile的第一行(或者在评论之后). (3认同)
  • 是否可以仅针对一个特定的制造目标更改SHELL变量,而使其他目标不变? (2认同)
  • 如果你使用 `/usr/bin/env bash`,它会使用 PATH 中的 `bash`。但是如果它只是`SHELL := bash`呢? (2认同)
  • 之前的评论不正确。`$(info $(SHELL))` 将_总是_显示 make 将调用的 shell,而不是调用 shell 的 `SHELL` 环境变量的值。如果“info”打印“/bin/bash”,则意味着在 makefile 中的某个位置您已将 makefile 变量“SHELL”设置为“/bin/bash”,这就是 make 在调用配方时将使用的 shell。 (2认同)

Chr*_*utz 17

你可以bash直接打电话,使用-c标志:

bash -c "diff <(sort file1) <(sort file2) > $@"
Run Code Online (Sandbox Code Playgroud)

当然,您可能无法重定向到变量$ @,但是当我尝试这样做时,我收到了-bash: $@: ambiguous redirect一条错误消息,因此您可能需要在进入此之前调查一下(尽管我是使用bash 3.2.something,所以也许你的工作方式不同).


Nic*_*all 6

一种可行的方法是将其放在目标的第一行中:

your-target: $(eval SHELL:=/bin/bash)
    @echo "here shell is $$0"
Run Code Online (Sandbox Code Playgroud)