julesbou julesbou - 5 months ago 14
Bash Question

Access variable declared inside Makefile command

I'm trying to access a variable declared by previous command (inside a Makefile).

Here's the

Makefile
:

all:
./script1.sh
./script2.sh


Here's the script declaring the variable I want to access,
script1.sh
:

#!/usr/bin/env bash
myVar=1234


Here's the script trying to access the variable previously defined,
script2.sh
:

#!/usr/bin/env bash
echo $myVar


Unfortunately when I run
make
,
myVar
isn't accessible. Is there an other way around? Thanks.

Answer

Make will run each shell command in its own shell. And when the shell exits, its environment is lost.

If you want variables from one script to be available in the next, there are constructs which will do this. For example:

all:
    ( . ./script1.sh; ./script2.sh )

This causes Make to launch a single shell to handle both scripts.

Note also that you will need to export the variable in order for it to be visible in the second script; unexported variables are available only to the local script, and not to subshells that it launches.

Comments