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 log
View commit history as a tree:
git log --oneline --graph --all
Show 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_name
Equivalent to:
git checkout -b branch_name
Switch branches or check out a specific commit:
git checkout <branch-or-commit>
See recently updated branches:
git branch --sort=-committerdate
Working with Changes
Temporarily save changes:
git stash
Apply the most recent stash:
git stash pop
List all stashes:
git stash list
Remove the last stash:
git stash drop
Remove all stashes:
git stash clear
Remove a specific stash:
git stash drop stash@{2}
Remove a file from staging:
git rm --cached path/to/file
Or, if you've already made at least one commit:
git restore --staged path/to/file
Undoing & Amending Changes
Quickly undo the last commit (but keep changes):
git reset --soft HEAD~1
or
git reset --mixed HEAD~1
--mixed
is the default; it also unstages changes.
Amend the last commit (edit message or add files):
git commit --amend
Great 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/file
Changing 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
pick
toedit
for 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 -sn
See 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_key
Set the remote URL to use a specific key:
git remote set-url origin git@github.com-personal:username/repo.git
Check your remotes:
git remote -v