2

We have a big make file that defines a lot of useful variables, like TEST_ENV. I'd like to make a shell script that lives in the same directory, and was wondering if there is any way to use the variables defined in the Makefile from the shell script. The variables I'm interested in are all defined like this

TEST_ENV := PATH=/path/to/thing \
            CONFDIR=/another/path

or

host_installdir = /still/a/path

The reason I want the script use the Makefile is so that if the variable ever needs to be changed inside the Makefile, the shell script won't get out of date.

I found this related question, but was hoping there might be a way to do this without having to run make first.

I considered the possibility of somehow using grep on the Makefile, but some of the variables are defined across multiple lines, which makes it tricky and breakable (for instance, if I do grep -A 3 for a variable defined across 3 lines, what if a 4th line is added later?).

2 Answers 2

2

You could use (a modified version of) the print-% target from Makefile hacks: print the value of any variable in your makefile to let you query it for values.

print-%:
        @echo '$(subst ','\'',$($*))'
Sign up to request clarification or add additional context in comments.

Comments

1
TEST_ENV=$(make -qp | awk -F' = ' '$1=="TEST_ENV" {print $2}')

I'm sure there are edge cases this doesn't handle, but it's a decent start. Rudimentary testing shows this handles multi-line variables.

5 Comments

I wasn't able to use your awk-only example, the $1==VARNAME never had any matches. I did get this related idea to work though: TEST_ENV=$(make -qp | grep "TEST_ENV :=" | awk -F ' := ' '{print $2}'). Thanks for the suggestion!
Looks like for your example the awk line needs -F' := '.
I did initially change the '=' to ':=' and ' := ', but it still was giving no results.
Did you write $1==VARNAME or $1=="VARNAME"? The quotes are required.
It depends on whether the variable is defined with = (deferred) or := (immediate), so the correct -F argument is -F ' :?= ' (although it is conceivable that the delimiter string will appear inside a variable definition). Note that make -p prints definitions, not values, so variables defined with = may have unexpanded variable references in the printed value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.