5

I want to run a script inside a makefile like this

    all: a b
    a:
        cd ~/trials; \
        . ./sx.sh
    b:
        echo $(bn)

sx.sh do this

    export bn=1

I don't see the variable in my terminal while issuing make command. My aim is to run a script before compiling my project for those script specific settings.

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
nikhil chaubey
  • 369
  • 1
  • 5
  • 11
  • 1
    This does not answer your question, but related information is here: http://stackoverflow.com/questions/23843106/how-to-set-environment-variable-in-makefile – Ben Hocking May 27 '15 at 11:43
  • So basically we can't run script inside a makefile to do the same. – nikhil chaubey May 27 '15 at 11:46
  • Just to be clear: this has absolutely nothing to do with make. It is not possible, in any (UNIX/POSIX) program, for the child process to modify the environment of its parent. It is never the case that a child shell can change the environment of its parent shell, for example, even leaving make out of the equation. – MadScientist May 28 '15 at 00:30

1 Answers1

4

You can't assume that the commands issued by make are all processed by the same instantiation of the shell. Make does not open a shell and feed it commands one-by-one and nor does it save the commands into a file and then feed it into a shell. It usually spawns a shell for each command like this:

$(SHELL) -c 'cd ~/trials; . ./sx.sh'

which means you cannot alter the environment and have it inherited by later commands.

The best way is to use make variables to store the specifics you wish to pass to the commands and use those variables in appropriate places.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • But I used to run a shellscript before giving make command. How those variables were being used by subshells? – nikhil chaubey May 27 '15 at 11:49
  • @nikhilchaubey Sub-shells of make will inherit from make, but make cannot inherit back from its own sub-shells. Environment variables can only be inherited down the tree and not up. If you set before running make it will then inherit from that shell that calls it, – Brian Tompsett - 汤莱恩 May 27 '15 at 12:45
  • 1
    @nikhilchaubey make, like all processes, inherits the environment of its parent process. In your normal shell when you source a script and set variables those are set in the current shell session and are available for other scripts/etc. running in that session. Additionally, anything `export`ed is available to child processes. – Etan Reisner May 27 '15 at 12:46
  • @EtanReisner Snap :-) – Brian Tompsett - 汤莱恩 May 27 '15 at 12:47