Skip to content

Instantly share code, notes, and snippets.

@harrastia
Last active November 22, 2017 12:58
Show Gist options
  • Save harrastia/f89d6d6d7818498278453047fb8d095c to your computer and use it in GitHub Desktop.
Save harrastia/f89d6d6d7818498278453047fb8d095c to your computer and use it in GitHub Desktop.
Git command to check out recently used branches
#!/bin/sh
# Carlos Arrastia (Holvi) 2017
#
# This script adds the git command "cor" which stands for CheckOut Recent.
# it lists the 10 most recently checked out branches and allows the user to select
# one for check out
#
# Usage:
#
# git cor
#
# extract the branch names out of the reflog checkout lines
lines=`git reflog | grep "checkout:" | sed -nE 's/.*moving from ([^ ]*).*/\1/p'`
# if execution of command git reflog failed (i.e: not in a repository
# directory) return with failure exit code
if [ $? -ne 0 ]; then exit 1; fi
# get a set with the 10 latest branches checked out
recent=""
for line in $lines; do
# add the branch to the list if it doesn't exist
match=`echo $recent | grep "\\b$line\\b"`
if [ -z "$match" ]; then
recent="$recent $line"
# and break the loop if the list has more 10 items or more
if [ `echo $recent|wc -w` -gt 9 ]; then
break;
fi
fi
done
# print the branches
echo "\nThese are the the 10 most recently checked out branches\n"
counter=0
for branch in $recent; do
echo "$counter) $branch"
counter=$((counter+1))
done
# ask user for selection
while true; do
echo ""
read -p "Select the branch number to check out 0-9 or q to quit: " sel
case $sel in
# if it is a number check out the branch matching the index
[0-9] )
counter=0
for branch in $recent; do
if [ $counter -eq $sel ]; then
git checkout $branch
break;
fi
counter=$((counter+1))
done
# print a fortune if available
if [ `which fortune` ]; then
echo
fortune -s
echo
fi
break;;
# exit if q is entered
[Qq]* ) exit;;
# notify of error with any other choice
* ) echo "Invalid choice.";;
esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment