Skip to content

Instantly share code, notes, and snippets.

@wearhere
Created May 19, 2012 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wearhere/2729195 to your computer and use it in GitHub Desktop.
Save wearhere/2729195 to your computer and use it in GitHub Desktop.
Checkout previous Git branch
#!/bin/sh
## Checks out the branch with the name recorded in the .PREVIOUS_BRANCH file
## in the working directory. To use this script, you should be using the
## post-checkout hook that creates such a file.
if [ ! -f ./.PREVIOUS_BRANCH ]
then
echo "No previous branch has been recorded. You're probably not using the post-checkout hook."
exit 1
fi
previous_branch=`cat ./.PREVIOUS_BRANCH`
git checkout ${previous_branch}
#!/bin/sh
## When the branch changes, record the name of the previously checked-out branch
## in a file called .PREVIOUS_BRANCH in the working directory.
## To use this script, place it in your .git/hooks directory, with the name "post-checkout".
## You should probably edit your .git/info/exclude file to ignore .PREVIOUS_BRANCH, too.
previous_ref=$1
heads_matching_previous_ref=`grep -r $previous_ref .git/refs/heads/*`
# http://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch#comment9751841_1593487
current_branch=`git symbolic-ref HEAD 2>/dev/null | cut -d"/" -f 3`
# the previous branch is the branch whose HEAD matches the previous ref,
# which is not the current branch (so that we ignore a newly forked & checked out branch)
# we assume that the user won't have 3 or more branches with the same HEAD
for head in $heads_matching_previous_ref
do
# heads are of the form .git/refs/heads/<branch>:<SHA>
branch=`echo ${head} | sed 's/\.git\/refs\/heads\/\(.*\)\:.*/\1/'`
if [ ${branch} != ${current_branch} ]
then
echo ${branch} > ./.PREVIOUS_BRANCH
break
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment