Skip to content

Instantly share code, notes, and snippets.

@mg98
Last active September 26, 2022 11:17
Show Gist options
  • Save mg98/7ca420b680d51b5e19baf28224166269 to your computer and use it in GitHub Desktop.
Save mg98/7ca420b680d51b5e19baf28224166269 to your computer and use it in GitHub Desktop.
Detect newly added vars in .env.example and automatically merge them into .env
#!/bin/bash
addedVars=$(git diff ORIG_HEAD HEAD --exit-code -- .env.example | tail -n +6 | grep '^\+' | sed '/^\+/ s/^\+//' | sed '/^[[:space:]]*$/d')
new=$(echo "$addedVars" | while read v; do
if [[ !$(cat .env | grep ^$v=) ]]; then
echo $v
fi
done)
if [[ "$new" ]]; then
printf "New environment variables detected:\n"
printf "$new"
printf "\n"
exec < /dev/tty
read -p "Merge to .env? (y/n) " -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
echo "$new" >> .env
fi
fi
@mg98
Copy link
Author

mg98 commented Sep 23, 2022

This script is meant to be added as post-merge hook under .git/hooks/post-merge in repositories. It will then be executed after every merge, including a git pull.

If the merge includes additions to .env.example and those additions represent variables that also do not exist in your local (gitignored) .env, it will offer to merge (add) those for you into this file.

It will NOT change variable values in your .env, nor will it ever delete variables.

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