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
  • -d includes untracked directories
  • -n is a dry run (preview only)
  • -f is required to actually allow git clean

Restore changes in working tree

git restore .
git restore name-of-the-file
  • git restore . restores all tracked files in the current directory tree
  • git restore name-of-the-file restores 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
  • -d refuses deletion if the branch is not merged
  • -D force deletes even if not merged

Detached HEAD quick recovery

  1. Create a commit while in detached HEAD
  2. Either switch to main and create a branch, or create it directly from current commit
  3. 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.