Skip to content

Instantly share code, notes, and snippets.

@schacon
Created January 13, 2024 18:41
Show Gist options
  • Save schacon/e9e743dee2e92db9a464619b99e94eff to your computer and use it in GitHub Desktop.
Save schacon/e9e743dee2e92db9a464619b99e94eff to your computer and use it in GitHub Desktop.
Better Git Branch output
#!/bin/bash
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
NO_COLOR='\033[0m'
BLUE='\033[0;34m'
YELLOW='\033[0;33m'
NO_COLOR='\033[0m'
width1=5
width2=6
width3=30
width4=20
width5=40
# Function to count commits
count_commits() {
local branch="$1"
local base_branch="$2"
local ahead_behind
ahead_behind=$(git rev-list --left-right --count "$base_branch"..."$branch")
echo "$ahead_behind"
}
# Main script
main_branch=$(git rev-parse HEAD)
printf "${GREEN}%-${width1}s ${RED}%-${width2}s ${BLUE}%-${width3}s ${YELLOW}%-${width4}s ${NO_COLOR}%-${width5}s\n" "Ahead" "Behind" "Branch" "Last Commit" " "
# Separator line for clarity
printf "${GREEN}%-${width1}s ${RED}%-${width2}s ${BLUE}%-${width3}s ${YELLOW}%-${width4}s ${NO_COLOR}%-${width5}s\n" "-----" "------" "------------------------------" "-------------------" " "
format_string="%(objectname:short)@%(refname:short)@%(committerdate:relative)"
IFS=$'\n'
for branchdata in $(git for-each-ref --sort=-authordate --format="$format_string" refs/heads/ --no-merged); do
sha=$(echo "$branchdata" | cut -d '@' -f1)
branch=$(echo "$branchdata" | cut -d '@' -f2)
time=$(echo "$branchdata" | cut -d '@' -f3)
if [ "$branch" != "$main_branch" ]; then
# Get branch description
description=$(git config branch."$branch".description)
# Count commits ahead and behind
ahead_behind=$(count_commits "$sha" "$main_branch")
ahead=$(echo "$ahead_behind" | cut -f2)
behind=$(echo "$ahead_behind" | cut -f1)
# Display branch info
printf "${GREEN}%-${width1}s ${RED}%-${width2}s ${BLUE}%-${width3}s ${YELLOW}%-${width4}s ${NO_COLOR}%-${width5}s\n" $ahead $behind $branch "$time" "$description"
fi
done
@FBen3
Copy link

FBen3 commented Apr 6, 2025

I think if [ "$branch" != "$main_branch" ] will always be True

  • main_branch=$(git rev-parse HEAD) will display the commit SHA
  • branch will display a string, e.g. dev

because of git for-each-ref --format="$format_string", each line will be abc1234@feature/login@2 days ago, then when we parse branch=$(echo "$branchdata" | cut -d '@' -f2), so branch = feature/login

Fix: main_branch=$(git rev-parse HEAD) --> main_branch=$(git rev-parse --abbrev-ref HEAD)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment