SKi
SKi

Reputation: 8476

How to prevent make to run $(shell command) too early

I want to create a file during a rule of a makefile, At the end of the rule, I want to run a shell command for the file by using $(shell xxx) function of make.

This is simplified example makefile for showing the problem:

test:
        @echo 123 >> file
        @cat file
        @echo "File: $(shell cat file) "

I expected that the last line of the makefile would print: File: 123

Instead it looks like that make runs $(shell cat file) before other lines of the makefile:

> rm file
> make test
cat: file: No such file or directory
123
File:  

Is there some simple way to prevent the unwanted behavior, and get the following kind of result?

> rm file
> make test
123
File: 123 

Upvotes: 1

Views: 550

Answers (3)

Victor Sergienko
Victor Sergienko

Reputation: 13485

Escape your dollars in Makefile and use shell's own subprocess facility, $(command).

test:
    echo "zzz" > z
    echo "$$(cat z)"

Upvotes: 1

Matt
Matt

Reputation: 15186

Is there some simple way to prevent the unwanted behavior

This is expected and documented behaviour. If that's not what you want, you mustn't use $(shell) at all.

test:
    @echo 123 >> file
    @cat file
    @printf "File: "
    @cat file

Upvotes: 1

G.M.
G.M.

Reputation: 12899

There's no need to use make's $(shell ... syntax here. Just use a backtick `...` sequence to invoke cat directly...

test:
        @echo 123 >> file
        @cat file
        @echo "File: "`cat file`

Or, if your version of echo supports the option to suppress the trailing newline...

test:
        @echo 123 >> file
        @cat file
        @echo -n "File: "; cat file

Upvotes: 2

Related Questions