How can I use Bash syntax in Makefile targets?

2019-01-04 07:54发布

I often find Bash syntax very helpful, e.g. process substitution like in diff <(sort file1) <(sort file2).

Is it possible to use such Bash commands in a Makefile? I'm thinking of something like this:

file-differences:
    diff <(sort file1) <(sort file2) > $@

In my GNU Make 3.80 this will give an error since it uses the shell instead of bash to execute the commands.

5条回答
Fickle 薄情
2楼-- · 2019-01-04 08:22

If portability is important you may not want to depend on a specific shell in your Makefile. Not all environments have bash available.

查看更多
Juvenile、少年°
3楼-- · 2019-01-04 08:27

You can call bash directly within your Makefile instead of using the default shell:

bash -c "ls -al"

instead of:

ls -al
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-04 08:29

There is a way to do this without explicitly setting your SHELL variable to point to bash. This can be useful if you have many makefiles since SHELL isn't inherited by subsequent makefiles or taken from the environment. You also need to be sure that anyone who compiles your code configures their system this way.

If you run sudo dpkg-reconfigure dash and answer 'no' to the prompt, your system will not use dash as the default shell. It will then point to bash (at least in Ubuntu). Note that using dash as your system shell is a bit more efficient though.

查看更多
爷、活的狠高调
5楼-- · 2019-01-04 08:32

From the GNU Make documentation,

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.

So put SHELL := /bin/bash at the top of your makefile, and you should be good to go.

BTW: You can also do this for one target, at least for GNU Make. Each target can have its own variable assignments, like this:

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"

That'll print:

a is /bin/sh
b is /bin/bash

See "Target-specific Variable Values" in the documentation for more details. That line can go anywhere in the Makefile, it doesn't have to be immediately before the target.

查看更多
Summer. ? 凉城
6楼-- · 2019-01-04 08:41

You can call bash directly, use the -c flag:

bash -c "diff <(sort file1) <(sort file2) > $@"

Of course, you may not be able to redirect to the variable $@, but when I tried to do this, I got -bash: $@: ambiguous redirect as an error message, so you may want to look into that before you get too into this (though I'm using bash 3.2.something, so maybe yours works differently).

查看更多
登录 后发表回答