Skip to content

Instantly share code, notes, and snippets.

@spoike
Created December 7, 2016 14:06
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 spoike/3c84325b2dc35d18bbdf630606c7d034 to your computer and use it in GitHub Desktop.
Save spoike/3c84325b2dc35d18bbdf630606c7d034 to your computer and use it in GitHub Desktop.
Git Checkout that remembers previous branch and lets you quickly switch between previous and current branches.
function gch() {
local currentBranch=$(git rev-parse --abbrev-ref HEAD)
local previousFile="$(git rev-parse --show-toplevel)/.git/PREVIOUS_HEAD"
if [ -n "$1" ]; then
echo "$currentBranch" >> $previousFile
git checkout "$@"
else
if [ ! -f "$previousFile" ]; then echo >&2 "ERROR: Missing PREVIOUS_HEAD. Please run gch with 1 argument first."
else
git checkout "$(cat $previousFile | tail --lines=1)"
echo "$currentBranch" >> $previousFile
fi
fi
# truncate the file
tail -n10 $previousFile > "$previousFile.TEMP"
mv -f "$previousFile"{.TEMP,}
}
@spoike
Copy link
Author

spoike commented Dec 7, 2016

Script is originally by skensell from this StackOverflow answer but has been modified to cache previous branch per-project under the project's .git folder in a PREVIOUS_HEAD file. It also works from any subfolder in the project.

@spoike
Copy link
Author

spoike commented Dec 7, 2016

Btw you can switch between branches with git checkout -.

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