Skip to content

Instantly share code, notes, and snippets.

@peterldowns
Last active January 14, 2025 21:03
Show Gist options
  • Save peterldowns/12a80929ebc626c1b30ea84245ff6960 to your computer and use it in GitHub Desktop.
Save peterldowns/12a80929ebc626c1b30ea84245ff6960 to your computer and use it in GitHub Desktop.
makefile-env-var-example
#!/usr/bin/env zsh
# Run the rule without either of the env vars defined;
# the output will show that neither variable is set.
echo "SOMEVARIABLE=$SOMEVARIABLE"
echo "ANOTHERVARIABLE=$ANOTHERVARIABLE"
make default
echo ""
# Run the rule with both env vars defined;
# the output will override the value of SOMEVARIABLE
# to be the value defined in the Makefile, and pass the ANOTHERVARIABLE
# through without overriding it.
export SOMEVARIABLE=somevalue
export ANOTHERVARIABLE=anothervalue
echo "SOMEVARIABLE=$SOMEVARIABLE"
echo "ANOTHERVARIABLE=$ANOTHERVARIABLE"
make default
## sets the value to literal empty string
SOMEVARIABLE := aaa
.PHONY: default
default:
@echo "showing the value of SOMEVARIABLE inside this make rule:"
@env | grep SOMEVARIABLE || echo "(not set)"
@echo "showing the value of ANOTHERVARIABLE inside this make rule:"
@env | grep ANOTHERVARIABLE || echo "(not set)"
SOMEVARIABLE=
ANOTHERVARIABLE=
showing the value of SOMEVARIABLE inside this make rule:
(not set)
showing the value of ANOTHERVARIABLE inside this make rule:
(not set)
SOMEVARIABLE=somevalue
ANOTHERVARIABLE=anothervalue
showing the value of SOMEVARIABLE inside this make rule:
SOMEVARIABLE=aaa
showing the value of ANOTHERVARIABLE inside this make rule:
ANOTHERVARIABLE=anothervalue
@peterldowns
Copy link
Author

I was extremely surprised to find that when running make default, the variables defined in the Makefile will be passed through as environment variables IFF there is an environment variable of the same name set in your shell when you run make.

This is sort of documented here but I wouldn't have guessed it behaved this way.

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