Discard unstaged changes in one file:
git restore path/to/fileDiscard unstaged changes in all tracked files:
git restore .Unstage files without touching the working tree:
git restore --staged path/to/file
git restore --staged .Remove untracked files:
git clean -nd # preview
git clean -fd # delete files and dirsAdd one file:
git add path/to/fileAdd everything:
git add -AStage selected hunks:
git add -pList branches:
git branch
git branch -r
git branch -aCreate and switch to a new branch:
git switch -c my-branchCreate a local branch that tracks a remote branch:
git switch --track origin/my-branchShow a compact graph:
git log --oneline --graph --decorate --allShow one commit:
git show <commit>Keep changes staged:
git reset --soft HEAD~1Keep changes unstaged:
git reset --mixed HEAD~1Replace main if your default branch is different.
git fetch origin
git switch my-branch
git rebase origin/mainIf there are conflicts:
git add <resolved-file>
git rebase --continue
git rebase --abortSquash the last n commits:
git rebase -i HEAD~nIn the editor keep the first commit as pick and change the rest to squash or fixup.
If the branch was already pushed:
git push --force-with-leaseRestore from HEAD:
git restore path/to/file-or-dirRestore from another commit:
git restore --source <commit> path/to/file-or-dirCheck the reflog:
git reflogCreate a branch from the old commit:
git branch recovered <commit>
git switch recoveredChange the message:
git commit --amendChange files in the last commit:
# edit files
git add -p # or: git add -A
git commit --amend
git push --force-with-leaseInstall pre-commit:
python3 -m venv .venv
. .venv/bin/activate
pip install pre-commit
pre-commit installThe config file is .pre-commit-config.yaml. Docs: https://pre-commit.com/
Rotate the secret first.
Rewrite history with git-filter-repo:
pip install git-filter-repo
printf 'old-secret==>REMOVED\n' > replacements.txt
git filter-repo --replace-text replacements.txt
git push --force --all
git push --force --tags