-
-
Save meros/c737a5acae910356d33b8391661dcbd9 to your computer and use it in GitHub Desktop.
A bash script to checkout a recently used branch again (useful when switching between branches often)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Check if fzf is installed | |
if ! [ -x "$(command -v fzf)" ]; then | |
# Check if brew is available | |
if [ -x "$(command -v brew)" ]; then | |
# Install fzf using brew if it is not installed | |
brew install fzf | |
else | |
# Print a message explaining how to install fzf manually | |
echo "❌ fzf is not installed. To install it, please follow the instructions at https://github.com/junegunn/fzf#using-git" | |
exit 1 | |
fi | |
fi | |
# Use `git reflog` to get a list of all branch names that were checked out | |
# Use `grep` to filter out only the lines that contain the string "checkout: moving from" | |
# This will include all lines in the reflog that indicate a branch was checked out | |
# Use `sed` to extract the branch name from each line | |
# Get only unique branch names (without reordering) | |
branches=$(git reflog | grep "checkout: moving from" | sed -E "s/.*moving from ([^ ]*) to.*/\1/" | awk '!seen[$0]++') | |
# Use fzf to let the user select a branch from the list | |
selected_branch=$( \ | |
echo "$branches" | \ | |
fzf --prompt="Select a branch to checkout: " \ | |
--height 10 \ | |
--border \ | |
--preview="git log --pretty=format:\"%C(yellow)%h%Creset %ad | %Cgreen%s%Creset %Cred%d%Creset %Cblue[%an]\" --date=short {}" \ | |
) | |
# Check if a branch was selected | |
if [ -z "$selected_branch" ]; then | |
# Print an error message if no branch was selected | |
echo "❌ No branch was selected. Exiting script." | |
exit 1 | |
fi | |
# Checkout the selected branch | |
git checkout $selected_branch | |
# Print a success message | |
echo "✅ Successfully checked out branch: $selected_branch" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment