- 1 year ago
Set environment variable on branch checkout/switch
To set an environment variable automatically when checking out or switching to a specific branch in Git, you can use Git hooks. Git hooks are scripts that are executed by Git in response to certain events, such as committing changes or checking out a branch.
To set an environment variable when checking out or switching to a specific branch, you can create a post-checkout hook script that sets the environment variable based on the name of the checked-out branch.
Here's an example of how to create a post-checkout hook script:
Create a file named
post-checkout
in the.git/hooks
directory of your Git repository.Add the following contents to the
post-checkout
file:
bash#!/bin/sh
branch_name="$(git symbolic-ref --short HEAD)"
if [ "$branch_name" = "your_branch_name" ]; then
export YOUR_VARIABLE_NAME="your_variable_value"
else
unset YOUR_VARIABLE_NAME
fi
In this example, the post-checkout
script uses the git symbolic-ref
command to get the name of the currently checked-out branch. If the name of the branch matches your_branch_name
, the script sets the YOUR_VARIABLE_NAME
environment variable to your_variable_value
. If the name of the branch does not match your_branch_name
, the script unsets the YOUR_VARIABLE_NAME
environment variable.
- Make the
post-checkout
file executable by running the following command:
bashchmod +x .git/hooks/post-checkout
After creating the post-checkout
script and making it executable, Git will automatically execute it each time you check out or switch to a new branch. If the name of the branch matches your_branch_name
, the YOUR_VARIABLE_NAME
environment variable will be set to your_variable_value
.
Note that the environment variable set by the post-checkout
script will only be available in the current shell session. If you want to make the environment variable available to other processes or shell sessions, you will need to set it globally in your operating system or export it from your shell.