Search code examples
bashshellmakefilegnu-makeheredoc

Makefile recipe with a here-document redirection


Does anyone know how to use a here-document redirection on a recipe?

test:
  sh <<EOF
  echo I Need This
  echo To Work
  ls
  EOF

I can't find any solution trying the usual backslash method (which basically ends with a command in a single line).

Rationale:

I have a set of multi-line recipes that I want to proxy through another command (e.g., sh, docker).

onelinerecipe := echo l1
define twolinerecipe :=
echo l1
echo l2
endef
define threelinerecipe :=
echo l1
echo l2
echo l3
endef

# sh as proxy command and proof of concept
proxy := sh

test1:
  $(proxy) <<EOF
  $(onelinerecipe)
  EOF

test2:
  $(proxy) <<EOF
  $(twolinerecipe)
  EOF

test3:
  $(proxy) <<EOF
  $(threelinerecipe)
  EOF

The solution I would love to avoid: transform multiline macros into single lines.

define threelinerecipe :=
echo l1;
echo l2;
echo l3
endef

test3:
  $(proxy) <<< "$(strip $(threelinerecipe))"

This works (I use gmake 4.0 and bash as make's shell) but it requires changing my recipes and I have a lot. Strip removes the newlines, from the macro, then everything is written in a single line.

My end goal is: proxy := docker run ...


Solution

  • Using the line .ONESHELL: somewhere in your Makefile will send all recipe lines to a single shell invocation, you should find your original Makefile works as expected.