Adding directory to PATH through Makefile

environment-variablesmakepath

I'm having some trouble in exporting the PATH I've modified inside the Makefile into the current Terminal. I'm trying to add to the PATH, the bin folder inside wherever the Makefile directory is.

Here's the relevant strip of the makefile:

PATH := $(shell pwd)/bin:$(PATH)

install:
    mkdir -p ./bin 
    export PATH
    echo $(PATH)

The echo prints it correctly but if I redo the echo in the terminal, the PATH remains the same.

Best Answer

You simply can't do this. There's no way¹ the make process can change its parent's environment (or its current directory, which you might be thinking of next).

In fact, even less is happending than you think.

  • Not all make implementations reflect the assignment to the make PATH variable in the environment; GNU make (found on Linux and other systems) does, but BSD make doesn't.
  • Each command line under a target runs in a separate subshell. (Except in some older BSD make implementations.) So the export PATH line is running on a shell that terminates immediately afterwards. Not that this line would be doing anything in the first place — if PATH is defined at that point, it's because it's in the shell's environment already.

Make is for building things automatically. If you want to set variables for your interactive environment, this isn't the tool you should be looking at. Instead, write a shell snippet, and source it in the current shell:

. ./define-my-variables.sh

In your makefile, source the script in every subshell. You can use a backslash to make a long command; remember that

  • The backslash-newline sequence is stripped by make, so the shell won't see a newline there.
  • Remember to prefix each line by a tab nonetheless.
  • Make's error behavior is to abort if a command fails. The shell won't do that by default, and the failure of any command but the last will go unnoticed by default, so you need to run set -e.
install:
    set -e; \
    . ./define-my-variables.sh; \
    mkdir -p bin; \
    …

¹ Obligatory note: no sane way. Even remotely invoking chdir via ptrace from a debugger won't work as is with most shells because they don't like to have their current directory changed under their feet.

Related Question