hewc
hewc

Reputation: 129

How to get a shell variable in a makefile?

in my Makefile, i want to get the read function return value. but it doesn't work

all: 
    git add .
    git commit -m $(shell read -r -p "please write some message: ")

Upvotes: 0

Views: 68

Answers (1)

MadScientist
MadScientist

Reputation: 100816

It's generally a bad idea to ask for input inside a makefile. Makefiles are intended to be non-interactive. You could instead require users to set a make variable with the message, like make all MSG='here is some message' and fail if it wasn't set.

However, if you really do want to do this interactively you have a number of problems.

First, make's shell function expands to the value that the shell prints to stdout, and the shell's read built-in doesn't write output to stdout; it stores that output in the $REPLY variable (or a different variable you provide. So if you wanted this to work it would have to be something like:

all:
        git add .
        git commit -m "$(shell read -r -p "please write some message: "; printf '%s\n' $$REPLY)"

But, it's almost always a mistake to use make's shell function inside a recipe: a recipe already runs in the shell, so trying to use make's shell function just adds confusion for no additional benefit.

Try:

all:
        git add .
        read -r -p "please write some message: "; git commit -m "$$REPLY"

Upvotes: 3

Related Questions