Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Bash syntax in Makefile targets?

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.

like image 726
Frank Avatar asked Feb 26 '09 05:02

Frank


People also ask

Can you use bash commands in a makefile?

So put SHELL := /bin/bash at the top of your makefile, and you should be good to go. 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.

What shell is used in makefile?

$(shell) $(shell) is a special function in gmake that runs an external command and captures the output for use in the makefile.

What is $$ in makefile?

$$ means be interpreted as a $ by the shell. the $(UNZIP_PATH) gets expanded by make before being interpreted by the shell.

How do I use bash shell?

Bash as a scripting language. To create a bash script, you place #!/bin/bash at the top of the file. To execute the script from the current directory, you can run ./scriptname and pass any parameters you wish. When the shell executes a script, it finds the #!/path/to/interpreter .


2 Answers

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.

like image 51
derobert Avatar answered Sep 21 '22 08:09

derobert


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).

like image 23
Chris Lutz Avatar answered Sep 17 '22 08:09

Chris Lutz