2

I'm using the git post-checkout hook in my repo to the current branch into a variable, I then want to use it else where like PHP etc.

Below is my post-checkout script:

#!/bin/bash
echo $GITBRANCH
GITBRANCH=`git symbolic-ref HEAD | cut -d/ -f3-`
echo $GITBRANCH
export $GITBRANCH

However it doesn't update. For example:

>git checkout master
Switched to branch 'master'
develop
master
>echo $GITBRANCH
develop

Running the GITBRANCH=git symbolic-ref HEAD | cut -d/ -f3- command on it's own will then produce the current branch name.

Why doesn't the hook update the $GITBRANCH variable globally?

2
  • 3
    I'm pretty sure you can't inject variables from your running process into the parent processes's environment in this way. Commented Oct 17, 2012 at 14:50
  • export allows a variable to be used by its child processes, not its parent process. Commented Oct 19, 2012 at 10:41

4 Answers 4

3

When you set the variable in a script, it'll be available only in the shell that the scripts runs in. As soon as the process terminates, the variable you set is gone forever!

If you want the variable available everywhere, probably .profile or .bashrc would be a better place.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately while that would make it available initially, when checking out new branches it wouldn't get updated still?
0

A two-step process should accomplish what you want:

1) In your post-checkout script, create a temporary file containing the variable you want to export. Something like

#!/bin/bash
GITBRANCH=`git symbolic-ref HEAD | cut -d/ -f3-`
echo "GITBRANCH=$GITBRANCH" > /tmp/new-branch

2) Create a bash function to act as a wrapper around git, and use that to source the temporary file after a checkout:

# Put this in .bashrc
git () {
    command git "$@"
    if [[ $1 = "checkout" ]]; then
        . /tmp/new-branch
    fi
}

$ git checkout master
Switched to branch 'master'
$ echo $GITBRANCH
master

2 Comments

Just had to put the full path to the git binary otherwise you get an endless loop.
You're right; I was testing a solution when I got busy something else. I think you can also use the command built-in to suppress function lookup, so that you can continue to use path lookup instead of hard-coded paths.
0

run the script with a dot in front of it.

. script

Comments

-1

Try:

export GITBRANCH

That is, without the dollar sign.

1 Comment

It's true that the dollar sign should not be used, but this will not fix his problem. It doesn't matter what gets exported; it's being exported to an environment that goes away when the script exits.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.