Git Commands Beyond add/commit/checkout
I decided that basic git add, git commit, and git checkout is not enough anymore, so I started a quick Git course to go deeper. I often end up in situations where I need more advanced commands, so here is my compact reference.
Preview clean-up before deleting files
git clean -dnf
-dincludes untracked directories-nis a dry run (preview only)-fis required to actually allowgit clean
Restore changes in working tree
git restore .
git restore name-of-the-file
git restore .restores all tracked files in the current directory treegit restore name-of-the-filerestores only one file
List tracked files
git ls-files
Shows files tracked by Git in the current repository.
Undo latest commit with reset
git reset --soft HEAD~1
Moves HEAD one commit back, but keeps changes staged.
git reset HEAD~1
Without --soft, reset is mixed by default:
- removes the latest commit
- keeps file changes in working directory
- unstages those changes
git reset --hard HEAD~1
Removes latest commit and discards corresponding working directory changes.
Delete branches safely or forcefully
git branch -d feature-branch
git branch -D feature-branch
-drefuses deletion if the branch is not merged-Dforce deletes even if not merged
Detached HEAD quick recovery
- Create a commit while in detached HEAD
- Either switch to main and create a branch, or create it directly from current commit
- If needed, create branch from explicit commit
git branch branch-name
git branch branch-name commit-id
Switch and merge
git switch master
git merge some-other-branch
.gitignore negation
*.log
!test.log
This ignores all .log files except test.log.