Git
Branches, commits, undoing changes, rebase, stash and searching history.
Everyday
Working tree status
git status -sbCreate a branch and switch to it
git switch -c <branch>
Commit all tracked changes
git commit -am "message"Push a new branch
git push -u origin <branch>
Pull with rebase
git pull --rebaseCompact history graph
git log --oneline --graph --decorate -20Undoing changes
Discard changes in a file
git restore <file>
Unstage a file
git restore --staged <file>
Amend the last commit
git commit --amend --no-editUndo the last commit, keeping changes
git reset --soft HEAD~1Create a commit that reverts another
git revert <commit>
Recover a “lost” commitadvanced
git reflogFind the hash you need and run git reset --hard <hash> or git cherry-pick <hash>.
Stash
Stash changes, including new files
git stash -uList stashes
git stash listApply the latest stash
git stash popAdvanced
Interactive rebase of the last N commitsadvanced
git rebase -i HEAD~<n>
Copy a commit onto the current branchadvanced
git cherry-pick <commit>
Find the commit that introduced a stringadvanced
git log -S "<text>" --oneline
Who last changed lines of a file
git blame -L 10,30 <file>
Binary search for the commit that introduced a bugadvanced
git bisect start && git bisect bad && git bisect good <commit>
Delete local branches already merged into mainadvanced
git branch --merged main | grep -v -E '^\*|main' | xargs -r git branch -dTags and remotes
Annotated tag and push it
git tag -a <git_tag> -m "Release <git_tag>" && git push origin <git_tag>
Delete a tag locally and on the remote
git tag -d <git_tag> && git push origin --delete <git_tag>
Show remotes
git remote -vChange the remote URL (e.g. to SSH)
git remote set-url origin <remote_url>
Delete remote-tracking branches that no longer exist
git fetch --pruneSync a fork with upstreamadvanced
git fetch upstream && git rebase upstream/mainWorktrees, submodules, history
Second working copy for another branch (no stash needed)advanced
git worktree add ../<branch> <branch>
Clone with submodules
git clone --recurse-submodules <remote_url>
Init and update submodules
git submodule update --init --recursiveChanges of a file over time (with renames)
git log --follow -p -- <file>
Commits in my branch that are not in main yet
git log --oneline main..<branch>
Pick one file from another branch
git restore --source <branch> -- <file>
Remove untracked files (dry run first)advanced
git clean -nd && git clean -fdShallow clone (only recent history)advanced
git clone --depth 1 <remote_url>