Create New Branch Only Contains Last N Commits

Sometimes we don’t need commit history from long time ago, and only want to keep last n commits. For example:

before:  A -> B -> C -> D -> E -> F -> G -> H -> I
now:     E -> F -> G -> H -> I  (only keeps last 5 commits)

Let’s say we want to perform this operation on our main branch, and backup the previous status as another branch main_old, then force push new main branch to the remote.

# store branch name and commit msg
$bname   = "main"
$msg     = "Initial commit message for the first commit"
$last_n  = 5

# create orphan branch
git switch $bname
git switch --detached head~$last_n
git checkout --orphan "${bname}-new"

# commit files
git add .
git commit -m $msg

# copy last n history
$n1 = $n - 1
git cherry-pick "${bname}~$n1..${bname}"

# change branch names
git branch -m $bname "${bname}-old"
git branch -m "${bname}-new" $bname

# set upstream
git branch --unset-upstream "${bname}-old"
git branch --set-upstream "origin/${bname}" $bname

The PowerShell script above will help us do the work.

Published by Oyasumi

Just a normal person in the world

Leave a Reply