Muja
Muja

Reputation: 55

Bash - String manipulation in Makefile

I've learned about string manipulation with bash, and more especially about substring replacement:

#! /bin/bash

VAR1="aaaa.bbbb.cccc"
VAR2="bbbb*"
echo ${VAR1%${VAR2}}

This bash script prints "aaaa.". I tried to include it in my makefile, but I can't make it work..

SHELL:=/bin/bash

VAR1="aaaa.bbbb.cccc"
VAR2="bbbb*"

all:
    @echo $${VAR1%$${VAR2}}

This Makefile only prints a blank line. I think I've misunderstood something, but can't figure out what. Any help would be really appreciated.

Upvotes: 3

Views: 5413

Answers (3)

chepner
chepner

Reputation: 531215

The problems is that VAR1 and VAR2 are not shell variables, but Makefile variables. To complicate matters further, each line in the Makefile recipe is executed in a separate shell process, which means the following naive attempt will fail:

all:
    VAR1="aaaa.bbbb.cccc"
    VAR2="bbbb*"
    @echo $${VAR1%$${VAR2}}

since VAR1 is defined in one shell, VAR2 in another, and the echo in a third where neither variable is defined. You could use the following:

all:
    @VAR1="aaaa.bbbb.cccc"; \
     VAR2="bbbb*"; \
     echo $${VAR1%$${VAR2}};

to have a single bash statement (all executed in one shell) split into multiple lines in the Makefile.

Upvotes: 4

jsj
jsj

Reputation: 9391

B̶a̶s̶h̶ ̶a̶n̶d̶ ̶M̶a̶k̶e̶ ̶d̶o̶ ̶n̶o̶t̶ ̶h̶a̶v̶e̶ ̶t̶h̶e̶ ̶s̶a̶m̶e̶ ̶s̶y̶n̶t̶a̶x̶.̶ ̶ ̶Y̶o̶u̶ ̶n̶e̶e̶d̶ ̶t̶o̶ You can use built-in make functions like (in this case) $(substr a,b,c)

See this

Upvotes: 0

chifung7
chifung7

Reputation: 2621

No need to put double quotes around VAR1 and VAR2. And you need to use export if you want to put VAR1 and VAR2 above all:

SHELL:=/bin/bash

export VAR1=aaaa.bbbb.cccc
export VAR2=bbbb*

all:
    @echo $${VAR1%$${VAR2}}

Upvotes: 5

Related Questions