Skip to content

Instantly share code, notes, and snippets.

@lengocthuong15
Last active September 21, 2021 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lengocthuong15/519fc48ba6a6376d423c62815840f01c to your computer and use it in GitHub Desktop.
Save lengocthuong15/519fc48ba6a6376d423c62815840f01c to your computer and use it in GitHub Desktop.
Git Tips n Tricks

Tips and tricks for git

How to cherry-pick a commit from another git repo?

First link the projects

cd /home/you/projectA
git remote add projectB /home/you/projectB
git fetch projectB

Then you can cherry-pick the commits:

git cherry-pick <first_commit>..<last_commit>

Ref: https://stackoverflow.com/questions/5120038/is-it-possible-to-cherry-pick-a-commit-from-another-git-repository

How to cherry-pick multiples commits?

To cherry-pick all the commits from commit A to commit B (where A is older than B), run:

git cherry-pick A^..B

If you want to ignore A itself, run:

git cherry-pick A..B

How to temporarily save your work when you need to change to another branch?

Git stash will help you do that

git stash

And then just jump to whatever you want, make some change, commit, and then go back to your previous branch. Pop what you have saved

git stash pop

To see the stash list

git stash list

Auto-squashing Git Commits

You have to rebase your commits, cause it has a lot of commits like: fix the typo, fix minor things, fix for commit abc, fix bla bla. And then you need to pick one by one. Well, you don't need to do it anymore. Just use auto-squash (not squat, ofc!).

For example, you have a git log like this

$ git log --oneline --decorate
ccc3333 (HEAD, my-feature-branch) A third commit
bbb2222 A second commit
aaa1111 A first commit
9999999 (main) Old stuff on main

And then you want to fix something related to the commit bbb2222, you modify the code and then you commit with --fixup

$ git add .
$ git commit --fixup bbb2222
[my-feature-branch ddd4444] fixup! A second commit

With --fixup, it will help you later on in the rebasing process. Now the git log looks like this:

$ git log --oneline --decorate
ddd4444 (HEAD, my-feature-branch) fixup! A second commit
ccc3333 A third commit
bbb2222 A second commit
aaa1111 A first commit
9999999 (main) Old stuff on main

So in the rebase step, rebase with the option --autosquash

git rebase --interactive --autosquash main

And bang, git will help you auto-squash

pick aaa1111 A first commit
pick bbb2222 A second commit
fixup ddd4444 fixup! A second commit
pick ccc3333 A third commit

Next time, don't forget to do your squat!

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