Git useful commands
Our brain is better at processing data than storing it. So that’s why I’m creating this document with one of the useful but maybe not so common commands to get the best for this wonderful tool
- Unstage all files you might have staged with git add
- Revert all local uncommitted changes:
git checkout .
- Revert all uncommitted changes:
git reset --hard HEAD
- Remove all local untracked files, so only git tracked files remain:
git clean -fdx
WARNING: -x will also remove all ignored files, including ones specified by .gitignore! You may want to use -n for a preview of files to be deleted.
- Delete all branches except the main one
git branch | grep -v "main" | grep -v "master" | xargs git branch -D
- Delete the most recent commit, keeping the work you’ve done:
git reset --soft HEAD~1
- Remove .git tracking
rm -rf .git
- Remove a file from a Git repository without deleting it from the local filesystem
git rm --cached .classpath
- If you have a sequence of commits
… - Commit1 - Commit2 - … Commit5 <- HEAD To squash Commit2 to Commit5 into a single commit, you can reset your branch to Commit1 and then commit again:
git reset --soft Commit1 git commit
- How to revert to origin’s master branch’s version of file
git checkout origin/master filename
- Resolve Git merge conflicts in favor of their changes during a pull In a conflicted state, and you want to just accept all of theirs:
git checkout --theirs . git add .
If you want to do the opposite:
git checkout --ours . git add .
git pull -X theirs
In a conflicted state by file
git checkout --theirs path/to/file