Stephan Richter
Stephan Richter

Reputation: 1156

Executable Makefile that runs in a specific directory

What I try to achieve:

What I have:

/docker/images/Makefile (with executable flag):

#!/usr/bin/make -f

default: ...
...

I can do

cd /docker/images
./Makefile

However, what I would like to be able to do:

cd /somewhere/else
/docker/images/Makefile

What I tried:

man make states, that I can set a --directoy <dir> param.
However, the shebang #!/usr/bin/make --directory=/docker/images -f, does not work:

$ cd /somewhere/else
$ /docker/images/Makefile
make: *** =/docker/images -f: Datei oder Verzeichnis nicht gefunden.  Schluss.

(File or dir not found)

Any guesses?
I'm on Devuan ASCII with GNU Make 4.1

I've seen the related thread which does not address my issue.

Upvotes: 0

Views: 742

Answers (4)

Philippe
Philippe

Reputation: 26727

When we put #!/usr/bin/make --directory=/docker/images -f

and run /docker/images/Makefile

It's equivalent to run :

/usr/bin/make "--directory=/docker/images -f" /docker/images/Makefile

One solution is to delegate to second line :

#!/home/debian/bin/run_second_line
# /usr/bin/make --directory=/docker/images -f

default: ...
...

In /home/debian/bin/run_second_line:

#!/bin/bash
get_second_line=$(awk 'NR == 2{print}' "$1")
exec bash -c "${get_second_line#?} $1"

Update :

It should work with this shebang:

#!/usr/bin/perl -euse File::Basename;exec qq`make -C @{[dirname $ARGV[0]]} -f ` . $ARGV[0]

Upvotes: 0

raspy
raspy

Reputation: 4261

Sure you can. Use /usr/bin/env with -S option, which is exactly meant for splitting parameters on the shebang line.

$ cat Makefile
#!/usr/bin/env -S make -C /docker/images -f
all:
        echo Foo

Output:

$ /docker/images/Makefile
make: Entering directory '/docker/images'
echo Foo
Foo
make: Leaving directory '/docker/images'

Upvotes: 2

Stephan Richter
Stephan Richter

Reputation: 1156

Inspired from similar approaches, I found a solution:

My makefile now has the following head:

#!/bin/bash

# the following block will be executed by bash, but not make
define BASH_CODE 2>/dev/null
make -C $(dirname $0) -f $(basename $0) $@
exit 0
endef

# the following lines will be interpreted by make, but not bash

# Makefile starts here #
volumes = $$HOME/docker/volumes

# headings created with https://www.askapache.com/online-tools/figlet-ascii/

default: talk

talk:
    @echo Dies ist ein Test
    pwd

...

With these lines in place I can now do the following:

  1. call make -C /path/to/makefile/
  2. call /path/to/makefile/Makefile

Anybody with a better solution?

Upvotes: 0

code_fodder
code_fodder

Reputation: 16391

What about just:

make -C /some/dir/where/there/is/a/makefile

Upvotes: 0

Related Questions