Last active
May 24, 2022 17:06
-
-
Save thalesmg/48e018afdb8d0f813e0c74366ed20e8b to your computer and use it in GitHub Desktop.
Makefile that watches for changes and passes arguments to rule
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Usage: | |
| # $ make test sailor | |
| # echo Hello, sailor! | |
| # Hello, sailor! | |
| # $ make watch test sailor | |
| # while true; do \ | |
| # make sailor; \ | |
| # inotifywait -qre close_write,create,delete .; \ | |
| # done | |
| # make[1]: Entering directory '/tmp/test' | |
| # make[1]: *** No rule to make target 'sailor'. Stop. | |
| # make[1]: Leaving directory '/tmp/test' | |
| # ./ CLOSE_WRITE,CLOSE other_file | |
| # make[1]: Entering directory '/tmp/test' | |
| # make[1]: *** No rule to make target 'sailor'. Stop. | |
| # make[1]: Leaving directory '/tmp/test' | |
| # If the first argument is "run"... | |
| ifeq (test,$(firstword $(MAKECMDGOALS))) | |
| # use the rest as arguments for "run" | |
| RUN_ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS)) | |
| # ...and turn them into do-nothing targets | |
| $(eval $(RUN_ARGS):;@:) | |
| endif | |
| # If the first argument is "watch"... | |
| ifeq (watch,$(firstword $(MAKECMDGOALS))) | |
| # use the rest as arguments for "watch" | |
| RUN_TARG := $(word 2,$(MAKECMDGOALS)) | |
| RUN_ARGS := $(wordlist 3,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS)) | |
| # ...and turn them into do-nothing targets | |
| $(eval $(RUN_ARGS):;@:) | |
| endif | |
| test: | |
| echo Hello, $(RUN_ARGS)! | |
| watch: | |
| while true; do \ | |
| make $(RUN_TARG) $(RUN_ARGS); \ | |
| inotifywait -qre close_write,create,delete .; \ | |
| done | |
| # References: https://stackoverflow.com/questions/2214575/passing-arguments-to-make-run | |
| # and https://stackoverflow.com/questions/7539563/is-there-a-smarter-alternative-to-watch-make |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment