DEV Community

Sabbir Siddiqui
Sabbir Siddiqui

Posted on

Git commands I find very useful and why

  1. git checkout [some-branch] -- [some/file/path.ts]
    This will check out (and stage) that specific file from that specific branch into your local branch. This is great for working in teams where changes are being made in the same codebase in parallel. Suppose in another branch your teammate wrote a util that you can also use, or if you yourself want to get the latest version of a file to remove avoid unnecessary merge conflicts. An alternative to these scenarios is:

  2. git cherry-pick [commit-hash]
    Get code from a specific commit into your own branch. You can use the --no-commit flag to stage the changes before committing them to your branch (in which case the history/hash will be changed). Useful if you want to copy over an exact commit from another branch to your own. Again, useful working in teams. Also useful if you yourself committed changes to the wrong branch, and you want to bring those changes over to the proper branch. After which you want to do:

  3. git reset [--hard] HEAD~[n]
    Let's say you committed directly in master branch because you forgot to checkout of your own branch. Or you pulled into a local branch that was rebased in remote and now your history is all messed up. Lots of different scenarios, one easy fix. The --hard reset will get rid of all changes permanently, so use this with extreme caution. Not using the --hard option will just remove the commit. For merge commits n=1 will work, but once the commits pile on it might get more difficult to use. Nevertheless, very useful.

  4. git commit --amend
    For when you want to make a small change to your previous commit but don't want to create a new commit. If you haven't pushed the branch then it works fine, if already pushed then you'll need to --force it, since you're effectively rewriting history :)

Discussion (2)

jdeepd profile image

For the last point,

if already pushed then you'll need to --force it, since you're effectively rewriting history

It is not recommended because if someone else had pulled the changes after you pushed to remote, then they will have a hard time pushing their changes once you ammend a commit and force push to remote.

siddiqus profile image
Sabbir Siddiqui Author

Definitely true. More so applicable for your own branches. Terrible if branches are either shared or common branches are needed.