0

I want to create a temporary file and pipe some text into it using a makefile.

In bash, I can create a temp file and pipe text into it like so:

temp_file=$(mktemp)
echo "text goes into file" > ${temp_file}
cat ${temp_file}
rm ${temp_file}

Output when running it (as expected):

    text goes into file

When using the same code in a makefile, I get the following output:

makefile:

test:
    temp_file=$(mktemp)
    echo "text goes into file" > ${temp_file}
    cat ${temp_file}
    rm ${temp_file}

$make test

    echo "text goes into file" >  /bin/sh: -c: line 1: syntax error near
    unexpected token `newline' /bin/sh: -c: line 1: `echo "text goes into
    file" > ' make: *** [makefile:18: test] Error 2

Any idea what I'm doing wrong here or if I'm missing any special makefile syntax rules?

6
  • To elaborate on the suggested previous answers: Each line of your makefile is executed in a separate shell, so the assignment from one line doesn't make it into the next one. You need to write either super long lines that do all at once or use .ONESHELL. – Wieland Feb 17 at 10:44
  • ... or use Makefile variables. – Stephen Kitt Feb 17 at 11:03
  • @Wieland: Yes, this worked for me. I managed to concatenate the lines with backslashes. Thanks! – karpfen Feb 17 at 11:04
  • @karpfen you’ve closed your question, which means I can’t answer it, but there is a better way to do this: write TEMP_FILE := $(shell mktemp) to declare a Makefile variable, then reference that in your recipe. – Stephen Kitt Feb 17 at 11:07