Skip to content

Instantly share code, notes, and snippets.

@lelanthran
Created March 13, 2023 05:46
Show Gist options
  • Save lelanthran/6c9bd1125f89e7621364878d1b97a5fc to your computer and use it in GitHub Desktop.
Save lelanthran/6c9bd1125f89e7621364878d1b97a5fc to your computer and use it in GitHub Desktop.
Use a stack to move between git branches.
#!/bin/bash
# Stores the current branch in a file so that popbranch can restore it later.
#
# Find the root of the git repo
while [ `ls -lad .git 2>&1 | grep -v 'No such file' | wc -l` -eq 0 ]; do
if [ $PWD == '/' ]; then
echo Not a git repo
exit 127
fi
cd ..
done
echo Found git root in $PWD
function die() {
echo $2
exit $1
}
function print_help_msg () {
echo '
GitBranchStack: stores current branch in a stack before changing to a new
branch. Return to previous branch by using the "pop" command
USAGE
xgit <pop | list | print | drop | help>
xgit <branch-name>
COMMANDS:
With no command specified, this message is printed. The first and only
argument to this program will be interpreted as the name of the branch to
switch to. When switching, the name of the current branch is pushed onto a
stack and the branch is changed to the specified branch.
When popping, the repo is switched to the branch name at the top of the
stack.
If the argument is one of pop, list, print, drop or help then the following
behaviour occurs:
help Display this message
list Displays all the branches in the stack
print Displays all the branches in the stack
drop Removes the last branch from the stack without switching to it.
'
}
function gbspop() {
NLINES=`wc -l < .gitbranchstack`
NEWBRANCH="`tail -n 1 .gitbranchstack`"
[ "$NLINES" -eq 0 ] && die 1 "Branch stack empty, doing nothing"
[ "$NEWBRANCH" == '' ] && die 2 "Branch stack empty, doing nothing"
git checkout "$NEWBRANCH" || die 127 "Failed to checkout branch"
NEWLINES=$(($NLINES - 1))
head -n $NEWLINES .gitbranchstack > /tmp/gbs.tmp
mv /tmp/gbs.tmp .gitbranchstack
}
function gbsdrop() {
NLINES=`wc -l < .gitbranchstack`
[ "$NLINES" -eq 0 ] && die 3 "Branch stack empty, doing nothing"
NLINES=$(($NLINES - 1))
BRANCHNAME="`head -n 1 .gitbranchstack`"
echo "Dropping branch '$BRANCHNAME' from stack"
tail -n $NLINES .gitbranchstack > xgit.tmpfile
mv xgit.tmpfile .gitbranchstack
}
BRANCH="`git branch | grep '*' | cut -f 2 -d \ `"
case "$1" in
pop) echo Popping over $BRANCH
gbspop
;;
list|print) cat .gitbranchstack
exit 0
;;
drop) echo Dropping one branch
gbsdrop
;;
''|help) print_help_msg
exit 0
;;
*) echo Pushing $BRANCH, switching to "$1"
git checkout "$1" && echo $BRANCH >> .gitbranchstack
;;
esac
echo "Done"
echo Current branch: `git branch | grep '*' | cut -f 2 -d \ `
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment