Essential Git Commands
Essential Git Commands
A collection of useful Git commands for everyday development, with explanations and examples.
Basic Operations
View commit history:
git logView commit history as a tree:
git log --oneline --graph --allShow differences between files or commits:
git diff <commit-hash> <file>Branch Management
Create and switch to a new branch (modern syntax):
git switch -c branch_nameEquivalent to:
git checkout -b branch_nameSwitch branches or check out a specific commit:
git checkout <branch-or-commit>See recently updated branches:
git branch --sort=-committerdateWorking with Changes
Temporarily save changes:
git stashApply the most recent stash:
git stash popList all stashes:
git stash listRemove the last stash:
git stash dropRemove all stashes:
git stash clearRemove a specific stash:
git stash drop stash@{2}Remove a file from staging:
git rm --cached path/to/fileOr, if you've already made at least one commit:
git restore --staged path/to/fileUndoing & Amending Changes
Quickly undo the last commit (but keep changes):
git reset --soft HEAD~1or
git reset --mixed HEAD~1--mixedis the default; it also unstages changes.
Amend the last commit (edit message or add files):
git commit --amendGreat for fixing typos, adding missing files, or cleaning up commit messages.
Restore a file from a previous commit:
git checkout <commit-hash> -- path/to/file- You can also specify multiple files.
Go back a number of commits:
git checkout <commit-hash>~1 -- path/to/fileChanging Commit Dates
Change the date of the last commit:
GIT_COMMITTER_DATE="2024-04-25T14:00:00" git commit --amend --no-edit --date "2024-04-25T14:00:00"Change the date of an older commit:
- Start an interactive rebase:
git rebase -i HEAD~3 - Change
picktoeditfor the commit you want to change. - When Git stops, run:
GIT_COMMITTER_DATE="2024-04-25T14:00:00" git commit --amend --no-edit --date "2024-04-25T14:00:00" - Continue the rebase:
git rebase --continue
Repository History & Contributors
See who has contributed and how many commits they've made:
git shortlog -snSee who made changes to specific lines in a file:
git blame -L 1,2 -w app/tldb/settings.py-L: Specify the line range (e.g., 1,2)-w: Ignore whitespace changes
Multiple SSH Keys for GitHub
Example ~/.ssh/config:
Host github.com-personal
HostName github.com
User git
IdentityFile ~/.ssh/personal_key
Host github.com-work
HostName github.com
User git
IdentityFile ~/.ssh/work_keySet the remote URL to use a specific key:
git remote set-url origin git@github.com-personal:username/repo.gitCheck your remotes:
git remote -v