Skip to content

Instantly share code, notes, and snippets.

@aprell
Last active November 11, 2021 12:53
Show Gist options
  • Save aprell/2b019eb37315e074821318aa14428c4a to your computer and use it in GitHub Desktop.
Save aprell/2b019eb37315e074821318aa14428c4a to your computer and use it in GitHub Desktop.
Makefile rule with multiline shell script recipe
all: foo.sh
check: foo.sh
@set -eu; \
echo "Running $<"; \
output=$$(sh $<); \
expect=42; \
if [ "$$output" != "$$expect" ]; then \
echo "*** CHECK FAILED: expected $$expect, got $$output"; \
fi
foo.sh:
echo "echo 42" > $@
clean:
rm -f foo.sh
.PHONY: all check clean
@aprell
Copy link
Author

aprell commented Aug 22, 2017

The recipe for check can be simplified by adding .ONESHELL:

.ONESHELL:
check: foo.sh
	@set -eu
	echo "Running $<"
	output=$$(sh $<)
	expect=42
	if [ "$$output" != "$$expect" ]; then
		echo "*** CHECK FAILED: expected $$expect, got $$output"
	fi

@davidmroth
Copy link

@aprell Great tip regarding .ONESHELL!!

@thiagobraga
Copy link

thiagobraga commented May 27, 2019

This was just what I needed. Many thanks for this tip.
In MacOS, for if statements with multiple lines work properly, I needed to update make from 3.81 to 4.2.1:

brew install make

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment