Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to source a script in a Makefile?

Tags:

shell

makefile

Is there a better way to source a script, which sets env vars, from within a makefile?

FLAG ?= 0 ifeq ($(FLAG),0) export FLAG=1 /bin/myshell -c '<source scripts here> ; $(MAKE) $@' else ...targets... endif 
like image 364
brooksbp Avatar asked Sep 21 '11 23:09

brooksbp


People also ask

How do I run a bash script in makefile?

Show activity on this post. which tells make to simply run a shell command. ./genVer.sh is the path (same directory as the makefile) and name of my script to run. This runs no matter which target I specify (including clean , which is the downside, but ultimately not a huge deal to me).

Can you use bash 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 is $$ in makefile?

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


Video Answer


2 Answers

Makefile default shell is /bin/sh which does not implement source.

Changing shell to /bin/bash makes it possible:

# Makefile  SHELL := /bin/bash  rule:     source env.sh && YourCommand 
like image 88
PureW Avatar answered Oct 27 '22 00:10

PureW


To answer the question as asked: you can't.

The basic issue is that a child process can not alter the parent's environment. The shell gets around this by not forking a new process when source'ing, but just running those commands in the current incarnation of the shell. That works fine, but make is not /bin/sh (or whatever shell your script is for) and does not understand that language (aside from the bits they have in common).

Chris Dodd and Foo Bah have addressed one possible workaround, so I'll suggest another (assuming you are running GNU make): post-process the shell script into make compatible text and include the result:

shell-variable-setter.make: shell-varaible-setter.sh     postprocess.py @^  # ... else include shell-variable-setter.make endif 

messy details left as an exercise.

like image 40
dmckee --- ex-moderator kitten Avatar answered Oct 26 '22 23:10

dmckee --- ex-moderator kitten