Makefile variable as prerequisite

后端 未结 8 609
清歌不尽
清歌不尽 2020-12-07 09:45

In a Makefile, a deploy recipe needs a environment variable ENV to be set to properly execute itself, whereas others don\'t care, e.g.:



        
8条回答
  •  执笔经年
    2020-12-07 10:02

    I know this is old, but I thought I'd chime in with my own experiences for future visitors, since it's a little neater IMHO.

    Typically, make will use sh as its default shell (set via the special SHELL variable). In sh and its derivatives, it's trivial to exit with an error message when retrieving an environment variable if it is not set or null by doing: ${VAR?Variable VAR was not set or null}.

    Extending this, we can write a reusable make target which can be used to fail other targets if an environment variable was not set:

    .check-env-vars:
        @test $${ENV?Please set environment variable ENV}
    
    
    deploy: .check-env-vars
        rsync . $(ENV).example.com:/var/www/myapp/
    
    
    hello:
        echo "I don't care about ENV, just saying hello!"
    

    Things of note:

    • The escaped dollar sign ($$) is required to defer expansion to the shell instead of within make
    • The use of test is just to prevent the shell from trying to execute the contents of VAR (it serves no other significant purpose)
    • .check-env-vars can be trivially extended to check for more environment variables, each of which adds only one line (e.g. @test $${NEWENV?Please set environment variable NEWENV})

提交回复
热议问题