Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash snippet doesn't work in makefile

I have one version file verfile which contains below version string
V1.1.2

And in Makefile I intend to read this version string, So I wrote Makefile as follows,

filepath        :=      $(PWD)
versionfile     :=      $(filepath)/verfile

all:
        cat $(versionfile)
        version=$(shell cat $(versionfile))
        echo "version=$(version)"

Now when I run the make file I get following ouput

cat /home/ubuntu/ankur/verfile
v1.1.2
version=v1.1.2
echo "version="
version=

So I am not able to store version string in the variable and use it later, I am not sure what am I doing wrong?

Any suggestion/pointer ?

After reading answer from "Didier Trosset" I changed my makefile as follows,

filepath        :=      $(PWD)
versionfile     :=      $(filepath)/verfile
myversion       :=      ""

all:

ifeq ($(wildcard $(versionfile)),)
all:
        echo "File not present"
else
all: myversion = $(shell cat $(versionfile))
endif
all:
        echo "myversion = $(myversion)"

and below is output for the

echo "myversion = v1.1.2"
myversion = v1.1.2
like image 602
ART Avatar asked Apr 05 '16 07:04

ART


People also ask

Can I use bash in makefile?

If this variable is not set in your makefile, the program `/bin/sh' is used as the shell. So put SHELL := /bin/bash at the top of your makefile, and you should be good to go.

What is $$ in makefile?

Double dollar sign If you want a string to have a dollar sign, you can use $$ . This is how to use a shell variable in bash or sh . Note the differences between Makefile variables and Shell variables in this next example.

What shell does makefile use?

By default make uses the /bin/sh shell. The default can be over ridden by using the variable SHELL = /bin/sh or equivalent to use the shell of your preference. This variable should be included in every descriptor file to make sure the same shell is used each time the descriptor file is executed.


1 Answers

You have two problems. First to have bash (and not make) expand the variable you need to use $$version (or $${version}). By this Make first translates $$ into just $ and then bash will see $version (or ${version}). Secondly each line in the rule will be executed as a separate command, so in order to let them interact via environmental variables you have to put them into a common subshell, enclosing with paranthesis.

filepath        :=      $(PWD)
versionfile     :=      $(filepath)/verfile

all:
    cat $(versionfile)
    (version=$(shell cat $(versionfile)); echo "version=$$version")
like image 190
hlovdal Avatar answered Sep 21 '22 23:09

hlovdal