How to get variables from the command line while makefile is runing?

31,036

Accessing shell variables

All exported shell environment variables are accessible like so:

$(MYBASEDIR)

Example

Say I have this Makefile.

$ cat Makefile 
all:
    @echo $(FOO)

Now with no variable set, big surprise, we get nothing:

$ printenv | grep FOO
$

$ make 

$

With the variable just set, but not exported:

$ FOO=bar
$ printenv |grep FOO
FOO=bar

$ export -p | grep FOO
$

$ make 

$

Now with an exported varible:

$ export FOO
$ export -p | grep FOO
declare -x FOO="bar"

$ make 
bar

Reading input from user

Sure you can read input from the user within a Makefile. Here's an example.

all:

    @echo "Text from env. var.: $(FOO)"
    @echo ""

    @while [ -z "$$CONTINUE" ]; do \
        read -r -p "Type anything but Y or y to exit. [y/N]: " CONTINUE; \
    done ; \
    [ $$CONTINUE = "y" ] || [ $$CONTINUE = "Y" ] || (echo "Exiting."; exit 1;)
    @echo "..do more.."

With this in place you can now either continue or stop the Makefile:

Example

Pressing y will continue:

$ make
Text from env. var.: bar

Type anything but Y or y to exit. [y/N]: y
..do more..
$

Pressing anything else such as n will stop it:

$ make
Text from env. var.: bar

Type anything but Y or y to exit. [y/N]: n
Exiting.
make: *** [all] Error 1

References

Share:
31,036

Related videos on Youtube

binghenzq
Author by

binghenzq

Updated on September 18, 2022

Comments

  • binghenzq
    binghenzq almost 2 years

    Such as in bash script: read -p "Only UI(y/n)" Temp_Answer. Is it possible to do this while Makefile is runing? Because I want to do different base on the $Temp_Answer (Y or N) in Makefile.

  • binghenzq
    binghenzq over 10 years
    @ slm - What can I do to keep makefile pause and ask input: Y or N like bask script? Any examples is helpful,and Thanks.
  • slm
    slm over 10 years
    @binghenzq - see update, shows how to read input too now.
  • bardiir
    bardiir over 6 years
    You should probably mention why there are backslashes in the user input. Without them it does not work i.e. using the variable in the next line does not work as the variables are not carried over from one of the subshells into the next.