git stash
and
git cherry-pick
Today's blog will briefly explain two powerful commands:
git stash
and
git cherry-pick
.
These commands are incredibly practical. They can be a lifesaver
when you're juggling multiple features in a project or when you've
made a mess of your branch and need a quick fix.
git stash
Git stash is used when you have made some changes locally but are
not ready to commit them yet and need to switch branches.
Let's
say you're working on a branch called
feature-A
, where
you made some changes, and now you need to switch to another branch,
let's say branch
feature-B
. How
would you do that without committing your local changes? Here comes
the need for git stash.
Simply run the command, and your local changes will be saved, while
your current code will be reverted to the HEAD commit. It's that
easy!
Once you're ready to continue working on that branch, you can do
git stash pop
,
and those local changes will return!
feature-A
branch; I've made some local changes that I don't want to commit
yet.
feature-B
feature-B
and
finish what's needed
feature-A
feature-A
git stash pop
That's it!
git cherry-pick
From its name,
git cherry-pick
lets you pick which commits you want to include in your branch.
Let's say you needed to merge your branch with another branch, and
you merged them incorrectly, where you deleted some important code
by mistake.
The easiest way to fix a corrupted branch is to create a new, clean
branch from your master or main branch and select the related
commits.
git cherry-pick {commit-hash}
git log
Those 2 commands are helpful in daily tasks, mainly when you need to switch branches quickly or fix an accidentally ruined branch.