Search code examples
gnu-makemakefile

Defining local variable in Makefile target


How to define local variable in Makefile target?

I would like to avoid repeating filename like:

zsh:
    FILENAME := "text.txt"
    @echo "Copying ${FILENAME}...";
    scp "${FILENAME}" "user@host:/home/user/${FILENAME}"

But I am getting an error:

FILENAME := "text.txt"
/bin/sh: FILENAME: command not found

Same with $(FILENAME)

Trying

zsh:
    export FILENAME="text.txt"
    @echo "Copying ${FILENAME} to $(EC2)";

Gives me an empty value:

Copying ...

Solution

  • You can't define a make variable inside a recipe. Recipes are run in the shell and must use shell syntax.

    If you want to define a make variable, define it outside of a recipe, like this:

    FILENAME := text.txt
    zsh:
            @echo "Copying ${FILENAME}...";
            scp "${FILENAME}" "user@host:/home/user/${FILENAME}"
    

    Note, it's virtually never correct to add quotes around a value when assigning it to a make variable. Make doesn't care about quotes (in variable values or expansion) and doesn't treat them specially in any way.