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
git reset
- 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 .
In pulling
git pull -X theirs
In a conflicted state by file
git checkout --theirs path/to/file
Top comments (1)
git reset --hard HEAD
Using it in this way is a bad idea. As you say it completely destroys all uncommitted changes in the working directory with no way to undo it. I suggest adding and using the following alias instead:
qWipe = '!git add -A && git commit -qm "SAVEPOINT" && git reset HEAD~1 --hard'
This will:
This creates a "hanging commit" and if nothing else happens it'll be garbage collected in due course (i think it's about a month IIRC by default).
But should you ever need to need to recover any of the changes you had before, that hanging commit can still be reached via the reflog.