Git Cool Commands:
git stash
and
git cherry-pick
Introduction
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.
Command#1:
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!
This is how it would look like in a real-life scenario
-
I'm working on a
feature-A
branch; I've made some local changes that I don't want to commit yet. -
I need to switch to another branch,
feature-B
- I run git stash
-
I switch (checkout) to
feature-B
and finish what's needed -
Now I'm ready to go back to
feature-A
-
I switch (checkout) to
feature-A
-
I run
git stash pop
That's it!
Command#2:
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.
Example
git cherry-pick {commit-hash}
git log
Summary
Those 2 commands are helpful in daily tasks, mainly when you need to switch branches quickly or fix an accidentally ruined branch.