Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save sandeepkv93/e6c5c2ce8f44df03bbf2d87c358c99f3 to your computer and use it in GitHub Desktop.

Select an option

Save sandeepkv93/e6c5c2ce8f44df03bbf2d87c358c99f3 to your computer and use it in GitHub Desktop.

✨ Move Top Commit to Stash and Rebase on Latest main

This guide shows how to take the top commit from your current branch, temporarily stash it, update your branch to match the latest main, and then re-apply the stashed changes.


🔧 Use Case

You’ve made one local commit on a feature branch but later realize you want that commit to apply on top of the latest main instead. Rather than rebasing or cherry-picking, you want to:

  1. Temporarily stash your top commit.
  2. Sync your branch with the latest main.
  3. Apply the changes back on top of main.

🧪 Step-by-Step Commands

1️⃣ Stash the top commit

# Move HEAD back one commit, but keep the changes staged
git reset --soft HEAD~1

# Stash the staged changes
git stash push -m "Top commit stash" --keep-index

✅ This saves your latest commit as a stash entry, and leaves your working tree clean.


2️⃣ Reset your branch to latest main

# Fetch the latest changes from remote
git fetch origin

# Hard reset your branch to match remote main
git reset --hard origin/main

⚠️ Warning: This will remove any uncommitted changes. Make sure everything is stashed or committed.


3️⃣ Apply the stashed changes on top of main

# Apply the stash
git stash pop

🧹 This applies the stashed commit and removes it from the stash list.


💡 Optional: View stash list

If you want to see the stashes before popping:

git stash list
git stash show -p stash@{0}

To apply a specific stash instead of popping:

git stash apply stash@{0}

🔁 Safer Alternative Without --hard Reset

If you prefer to avoid a hard reset (for safety):

git stash push -m "Top commit stash"
git fetch origin
git reset --merge origin/main
git stash pop

--merge will preserve local changes unless there are conflicts.


✅ End Result

You now have your latest changes re-applied on top of the most recent main, as if you had committed them freshly after syncing with the base branch.


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