How to source a script in a Makefile?

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

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.

Tags:

Shell

Makefile