git-hooks/add-app-version-to-env-file.md

850 B

Be warned that the sed command used will overwrite the entire line when the string is found.

If you want to add a git hash or version to an environment file, such as in a Laravel project, you can use this:

Filename: .git/hooks/post-commit

#!/bin/sh

# Redirect output to stderr.
exec 1>&2

GIT_HASH=$(git rev-parse --short HEAD)
echo "Applying the following hash: $GIT_HASH"
sed -i "/APP_GIT_HASH/c\APP_GIT_HASH=\"${GIT_HASH}\"" .env

If you would like to have which branch/tag you are using written to the environment file every time you checkout a new branch/tag, you can use this:

#!/bin/sh

# Redirect output to stderr.
exec 1>&2

GIT_BRANCH=$(git symbolic-ref -q --short HEAD || git describe --tags --exact-match)
echo "Applying the following hash: $GIT_BRANCH"
sed -i "/APP_VERSION/c\APP_VERSION=\"${GIT_BRANCH}\"" .env