user1343585
user1343585

Reputation: 699

How to read the first line of a text file and assign it to a variable in a makefile?

I have a file named info.txt. I want to read the first line of the file and assign it to a variable BUILD_NO in a makefile. How do I do it?

Upvotes: 0

Views: 1536

Answers (2)

MadScientist
MadScientist

Reputation: 100816

If you're OK with the value only being available in a command script, and you're not worried about it being quoted, Jonathan's solution will work very well. If you want it available in the makefile as well, or you're concerned about things like '$(BUILD_NO)' appearing in your scripting, and you're willing to restrict yourself to GNU make, you can use:

BUILD_NO := $(shell head -n 1 info.txt)

(I use head here just because it's slightly more efficient). There are alternatives in some other versions of make but, unfortunately, nothing truly portable.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753575

BUILD_NO = `sed 1q info.txt`

When you reference ${BUILD_NO} or $(BUILD_NO) in an action, the shell fragment will be executed. You might decide you want double quotes around it too:

BUILD_NO = "`sed 1q info.txt`"

If you want that in dependency information, you have to work a bit harder — which version of make are you using on which platform?

Upvotes: 0

Related Questions