Skip to content

Git: Automate Branch Selection, Creation, and Deletion

Source: Notion | Last edited: 2024-09-07 | ID: 782c8373-d29...


This script is intended for Git users who frequently manage branches in their repositories. It is especially useful for developers who need to switch between branches, create new branches, or delete existing branches efficiently.

The script automates the process of selecting, creating, and deleting Git branches. It uses fzf for interactive branch selection and provides colorized output for better readability.

Use this script whenever you need to:

  • Switch to a different branch.
  • Create a new branch and switch to it.
  • Delete an existing branch.

Run this script in your terminal within the root directory of your Git repository.

Managing branches manually can be time-consuming and error-prone. This script simplifies the process by providing an interactive interface for branch selection and automating common tasks like branch creation and deletion.

Follow these steps to use the script:

  1. Copy the Script: Copy the entire script below.
  2. Paste into Terminal: Open your terminal and paste the script. Press Enter to execute it.
  3. Follow the Prompts: The script will guide you through selecting an action (create, switch, or delete a branch) and will handle the rest automatically.
Terminal window
# Script to automate branch selection, creation, and deletion
# Create a temporary script file
temp_script=$(mktemp)
# Write the script content to the temporary file
cat << 'EOF' > "$temp_script"
#!/bin/bash
# Function to add color
colorize() {
local color_code="\033[$1m"
local text="$2"
local reset="\033[0m"
echo -e "${color_code}${text}${reset}"
}
# Function to clean branch name
clean_branch_name() {
local branch_name="$1"
branch_name=$(echo "$branch_name" | sed 's/.*\x1b\[m //; s/\x1b\[[0-9;]*m//g') # Remove color codes
branch_name=$(echo "$branch_name" | sed 's/^\* //') # Remove leading '*'
branch_name=$(echo "$branch_name" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') # Trim whitespace
echo "$branch_name"
}
# Function to select and clean a branch name using fzf
select_and_clean_branch() {
local prompt="$1"
local branches="$2"
local selected_line=$(echo "$branches" | fzf --ansi --layout=default --prompt="$prompt" --bind 'esc:abort,ctrl-c:abort')
if [ -z "$selected_line" ]; then
echo "Selection aborted. Exiting script."
exit 0
fi
local selected_branch=$(echo "$selected_line" | awk -F' | ' '{print $1}')
echo $(clean_branch_name "$selected_branch")
}
# Function to switch to a branch
switch_to_branch() {
local branch_name="$1"
echo "Switching to branch '$branch_name'..."
if git switch "$branch_name"; then
echo "Switched to branch '$branch_name'."
else
echo "Failed to switch to branch '$branch_name'. Aborting."
exit 1
fi
}
# Function to delete a branch
delete_branch() {
local branch_name="$1"
echo "Deleting local branch '$branch_name'..."
if git branch -d "$branch_name"; then
echo "Deleted local branch '$branch_name'."
else
echo "Failed to delete local branch '$branch_name'."
fi
}
# Function to handle deletion of a branch
handle_branch_deletion() {
local branch_name="$1"
echo -e "\033[1;31mAre you sure you want to delete the local branch '$branch_name'? (y/n):\033[0m"
echo "Note: This action will permanently delete the local branch '$branch_name'."
echo "If you have any uncommitted changes or important work on this branch, please make sure to save it before proceeding."
read -p "Press Enter to continue..." # Pause for user to read
read -p "" confirm
if [ "$confirm" = "y" ]; then
echo "User confirmed deletion of local branch '$branch_name'."
delete_branch "$branch_name"
else
echo "Local branch deletion aborted by user."
fi
}
# Function to fetch branches with detailed information and colorize output
fetch_branches() {
local ref_type="$1"
local sort_order="$2"
git for-each-ref --sort="$sort_order" "$ref_type" --format='%(refname:short) | %(authorname) | %(authordate:relative) | %(subject)' | while IFS='|' read -r refname authorname authordate subject; do
echo -e "\033[1;34m${refname}\033[0m | \033[1;32m${authorname}\033[0m | \033[1;33m${authordate}\033[0m | \033[1;37m${subject}\033[0m"
done
}
# Function to handle branch creation and switching
create_and_switch_branch() {
# Prune and fetch remote branches to ensure we have the latest information
prune_and_fetch_branches "refs/remotes/" "-committerdate"
# Prompt user to select a remote branch to base the new local branch on
echo "Please select a remote branch to base the new local branch on."
echo "This will create a new local branch that tracks the selected remote branch."
echo "On the next screen, you will see a list of remote branches to choose from."
read -p "Press Enter to continue..." # Pause for user to read
selected_branch=$(select_and_clean_branch "Select a branch to switch to: " "$branches")
echo "Debug: selected_branch='$selected_branch'" # Debug log
echo "User selected branch '$selected_branch' to switch to."
# Prompt user to enter a name for the new local branch
echo "Please enter a name for the new local branch."
echo "This will be the name of the new branch created locally."
read -p "Press Enter to continue..." # Pause for user to read
read -p "Enter a name for the new local branch: " local_branch_name
echo "User entered '$local_branch_name' as the name for the new local branch."
# Create and switch to the new local branch
echo "Creating and switching to the new local branch '$local_branch_name' tracking '$selected_branch'..."
git switch -c "$local_branch_name" "$selected_branch"
git push --set-upstream origin "$local_branch_name"
echo "Branch '$local_branch_name' created and set up to track '$selected_branch'."
# Confirm if everything is as expected
echo "Please confirm if everything is as you wanted."
echo "If you are not satisfied with the branch creation, the current branch will be deleted."
read -p "Press Enter to continue..." # Pause for user to read
read -p "Is everything as you wanted? (y/n): " confirmation
if [ "$confirmation" != "y" ]; then
echo "User indicated that everything is not as expected."
delete_current_branch
else
echo "Branch creation confirmed by user."
fi
}
# Function to handle deletion of the current branch
delete_current_branch() {
# Get the name of the current branch
current_branch=$(git symbolic-ref --short HEAD)
echo "Current branch is '$current_branch'."
# Prune and fetch local branches to ensure we have the latest information
prune_and_fetch_branches "refs/heads/" "-committerdate"
# Exclude the current branch from the selection
remaining_branches=$(echo "$branches" | grep -v "$current_branch")
# Prompt user to select a branch to switch to before deleting the current branch
echo "Please select a branch to switch to before deleting the current branch."
echo "This will ensure you are not left without a branch to work on."
echo "On the next screen, you will see a list of branches to switch to."
read -p "Press Enter to continue..." # Pause for user to read
branch_to_switch_name=$(select_and_clean_branch "Select a branch to switch to: " "$remaining_branches")
echo "Debug: branch_to_switch_name='$branch_to_switch_name'" # Debug log
echo "User selected branch '$branch_to_switch_name' to switch to before deleting the current branch."
# Switch to the selected branch
switch_to_branch "$branch_to_switch_name"
# Handle deletion of the current branch
handle_branch_deletion "$current_branch"
}
# Function to handle deletion of another branch
delete_another_branch() {
# Get the name of the current branch
current_branch=$(git symbolic-ref --short HEAD)
# Prune and fetch local branches to ensure we have the latest information
prune_and_fetch_branches "refs/heads/" "-committerdate"
# Exclude the current branch from the selection
remaining_branches=$(echo "$branches" | grep -v "$current_branch")
# Prompt user to select a branch to delete
echo "Please select a branch to delete."
echo "Note: This action will permanently delete the selected branch."
echo "If you have any uncommitted changes or important work on this branch, please make sure to save it before proceeding."
echo "On the next screen, you will see a list of branches to delete."
read -p "Press Enter to continue..." # Pause for user to read
branch_to_delete_name=$(select_and_clean_branch "Select a branch to delete: " "$remaining_branches")
echo "Debug: Cleaned branch_to_delete_name='$branch_to_delete_name'" # Debug log
echo "User selected branch '$branch_to_delete_name' to delete."
# Handle deletion of the selected branch
handle_branch_deletion "$branch_to_delete_name"
}
# Function to prune and fetch branches
prune_and_fetch_branches() {
local ref_type="$1"
local sort_order="$2"
echo "Pruning remote branches to remove references to deleted branches..."
git fetch --prune
echo "Fetching branches..."
branches=$(fetch_branches "$ref_type" "$sort_order")
if [ -z "$branches" ]; then
echo "No branches found. Exiting script."
exit 1
fi
}
# Master top selector
echo "Select an action:"
echo "Please choose one of the following actions:"
echo "1. Create and switch to a new branch: This will create a new local branch based on a selected remote branch and switch to it."
echo "2. Delete the current branch: This will delete the branch you are currently on after switching to another branch."
echo "3. Delete another branch: This will delete a branch other than the one you are currently on."
echo "On the next screen, you will see these options to select from."
read -p "Press Enter to continue..." # Pause for user to read
action=$(echo -e "Create and switch to a new branch\nDelete the current branch\nDelete another branch" | fzf --ansi --layout=default --prompt="Select an action: " --bind 'esc:abort,ctrl-c:abort')
if [ -z "$action" ]; then
echo "Selection aborted. Exiting script."
exit 0
fi
echo "Action selected: $action"
case "$action" in
"Create and switch to a new branch")
create_and_switch_branch
;;
"Delete the current branch")
delete_current_branch
;;
"Delete another branch")
delete_another_branch
;;
*)
echo "Invalid action selected. Exiting script."
exit 1
;;
esac
EOF
# Make the temporary script executable
chmod +x "$temp_script"
# Run the temporary script
"$temp_script"
# Clean up by removing the temporary script
rm "$temp_script"
  • Who: Git users, especially developers.
  • What: Automates branch selection, creation, and deletion.
  • When: Whenever you need to manage branches.
  • Where: In the terminal within your Git repository.
  • Why: To save time and reduce errors in branch management.
  • How: Copy and paste the script into your terminal and follow the prompts. This tutorial should help you understand and use the script effectively.