Configure
# Config username and email
git config --global user.name jdoe
git config --global user.email [email protected]
# To avoid detected dubious ownership warning
git config --global --add safe.directory "*"
Initialize Repository
git init # Create a new Git repository
git clone <url> # Clone an existing repository
Working with Changes
git status # Show the working directory status
git add -A # Stage all changes
git add <file> # Stage a specific file
git reset # Unstage all files (keep changes)
git reset <file> # Unstage a specific file
git mv <source> <dest> # Rename file
git checkout -- <file> # Revert local file changes
# Revert changes on single file to previous commit
git checkout <commit-hash> <file>
# Revert changes made by specified commit
git revert <commit-hash>
Commit & History
git commit -m "Message" # Commit with a message
git log # View commit history
git log --oneline # Compact log view
git log -3 --name-status # Last 3 changes with file names
git log --follow -p -- <file> # Follow file history
Blame
# Blame from line X to Y
git blame -L X,Y <file>
# Show changes on a file from a specified commit
git show <commit-hash> -- <file>
Push & Pull
git push origin <branch> # Push changes to the remote branch
git push origin -u <branch> # Push new branch
git pull # Fetch and merge changes from remote
git fetch --all # Fetch all from remote
# Delete branch from remote
git push origin --delete <branch>
Patching
# Patch from uncommitted changes
git diff > changes.patch
# Patch from changes between two commits
git diff commit1 commit2 > changes.patch
Branching
git branch # List all branches
git branch <name> # Create a new branch
git branch -d <name> # Delete a branch
git checkout <branch> # Switch to a branch
git checkout -b <name> # Create and switch to a new branch
git merge <branch> # Merge a branch into the current one
Tagging
git tag <name> # Create new tag
git push origin --tags # Push tags to remote
# Tag with current date / time
git tag PUB_$(date -Format 'yyMMdd')
git tag PUB_$(date -Format 'yyMMdd-HHmm')
Undoing Changes
git restore <file> # Discard changes in a file
git reset --hard # Discard all uncommitted changes
Remote Repositories
git remote -v # Show remote repositories
git remote add origin <url> # Add a remote repository
git remote rm origin # Remove a remote repository