git last
cd -
and git checkout -
both switch back to the previous folder and branch you were on, respectively.
I use this frequently but it doesn’t work so well with git
because more often than not I switched to main
in between the two branches. git last
was made to solve this:
git last
Displays the last 10 branches you were on, and allows you to switch to one of them. Usage:
$ git last
1 aitah_judgement_bot
2 comment_posting_class
3 fix_codespaces
4 fix_reddit_authed_requests
5 schedule
6 display_number_of_post_sentences
7 separate_daily_jobs_into_3_schedules
8 new_devcontainer
9 fix_logs_controller_cant_find_track_event
10 fix_logs_controller_error
Enter the number of the branch you want to checkout (or press Enter to skip): 3
Switched to branch 'fix_codespaces'
[~/workspace/aitah-player]─[±] fix_codespaces {29} ✓
Below is the script. Place it anywhere in your path, and git
will be smart enough to translate git last
to git-last
:
git-last
:
#!/bin/bash
# Get the current branch name
current_branch=$(git rev-parse --abbrev-ref HEAD)
# Generate the list of branches excluding the current one and non-existent branches
branches=$(git reflog --date=iso | grep checkout | awk '/checkout: moving from/ {print $8}' | grep -v '^[0-9a-f]\{40\}$' | grep -v "$current_branch" | awk '!seen[$0]++' | while read branch; do
if git show-ref --verify --quiet refs/heads/$branch; then
echo $branch
fi
done | head -n 10)
# Print the branches with line numbers
echo "$branches" | nl -n ln
# Ask the user to select a branch
read -p "Enter the number of the branch you want to checkout (or press Enter to skip): " branch_number
# Check if branch_number is not empty
if [ -n "$branch_number" ]; then
# Get the name of the selected branch
branch_name=$(echo "$branches" | sed "${branch_number}q;d")
# Check if the branch name is not empty
if [ -n "$branch_name" ]; then
# Checkout the selected branch
git checkout "$branch_name"
else
echo "Invalid branch number. Skipping checkout."
fi
else
echo "No branch number entered. Skipping checkout."
fi