Daily Git Commands
Sequence of Git commands I use when implementing a new feature a.k.a my mostly used git commands
- git checkout master — I make sure I work on top of the master branch
- git pull origin master —I make sure that my repository is updated with the latest version
- git checkout -B <feature/A> — Checkout a new branch for the feature
- git stash — I want to save my rough draft and get back to it later, but it’s not ready for a
commit
just yet - git stash apply — Apply my rough draft #4, I want to continue working on it
4 & 5 don’t always happen, but I do it especially if want to checkout and review other branches
6. git add . — My changes look good, I want to commit
them
7. git commit -m “Add this feature” — Commit changes and add a clear description
8. git push origin HEAD — Push this branch to remote repository
The above scenario is the simplest. But most of the time it’s more complicated and looks like this
6. git add . && git commit -m “Update implementation”
7. git add . && git commit -m “Add a small fix”
8. git add . && git commit -m “Add another fix”
As seen, I committed some little changes, but it made my commit history kinda “dirty”. So, I cleanup my commit history by rebasing interactively.
9. git rebase -i HEAD~(n) — Cleanup commits and messages, where n is the number of commits I wanted to edit starting from HEAD
In this case (git rebase -i HEAD~4). Then, I either pick, fixup, reword, or drop some commits
- pick -> use commit
- fixup (f) -> squash, by discard the commit’s log message
- drop (d) -> remove commit
- reword (r) -> edit commit messsage
After rebasing, all that is left is the commit I picked, in this case commit “Add feature A”. Fixed-up (f) commits will be squashed to the previous commit, and dropped (d) commits will be removed.
10. git push origin HEAD -f — Force push the changes especially since we’re rebasing. Caveat ⚠️ it will overwrite your remote branch
That’s it! The branch is ready for Pull Request. ✨
Note: branch feature/A is not necessary a feature but more of a small Pull Request (PR). I like small PRs, I usually chop down a big feature into small PRs.