Naren

git

The commands that undo things, and the ones that find things.

Verified against git 2.50.1.

Commands

Move between branches and restore files, without checkout doing both jobs:

git switch -c new-branch
git switch -            # back to the previous branch
git restore --staged FILE   # unstage, keep the edit
git restore FILE            # throw the edit away

Find the commit that introduced a string, not just the ones mentioning it:

git log -S"functionName" --oneline
git log -L :functionName:path/to/file.ts

Fix an earlier commit without an interactive rebase dance:

git commit --fixup=COMMIT
git rebase -i --autosquash COMMIT~1

Push a rebased branch without overwriting someone else's work:

git push --force-with-lease

Find where it broke, in log time:

git bisect start HEAD GOOD_COMMIT
git bisect run ./test.sh

Recover a commit you think you destroyed:

git reflog
git switch -c rescue HEAD@{3}

Two branches checked out at once, without stashing:

git worktree add ../hotfix main
git worktree list

Blame that ignores whitespace and follows moved code:

git blame -w -C -C FILE

See what clean would delete before it deletes it:

git clean -nd

Notes

--force-with-lease refuses the push when the remote moved since you last fetched. Plain --force does not, which is how a colleague's commit disappears.

git bisect run takes any command. Exit 0 means good and exit 1 means bad, so a one line shell script is usually enough.

-C in blame finds code moved from another file. Passing it twice, as above, widens the search to the commit that created the file.

reflog is local and expires, by default after 90 days. It cannot recover anything from a clone you deleted.

On this page