Configuration
git config --global core.editor "vim"
Discarding Modifications
// Unstage files from the index
# Step 1: Move changes from index to working directory
git reset HEAD path/to/file
# Step 2: Discard changes in the working directory
git checkout -- path/to/file
// Restore a specific file to a previous revision
git checkout <commitHash> -- <filename>
Consolidating Commits
git rebase -i HEAD~3 // Or specify a starting commit_id
# Commands available during rebase:
# pick: Use the commit as is (default)
# squash: Combine this commit with the previous one
# fixup: Combine with the previous commit, discarding this log message
# drop: Remove the commit entirely
// Modifying the most recent commit:
git commit --amend
Force Local Overwrite
git fetch --all
git reset --hard origin/main
Inspecting History
// Show changes introduced by a specific commit
git show <commit-hash> [<filename>]
// Show file statistics for a specific commit
git show <commit-hash> --stat
// Show recent commit history with stats
git log -2 --stat
// Compact log view
git log --pretty=oneline
// Reference log: tracks all operations including deleted commits
git reflog
Initializing Remote Repository
git init
git remote add origin https://github.com/username/repository.git
git pull --rebase origin main // Use 'git pull origin main' if rebase is not desired
// Set upstream to avoid specifying remote branch later
git branch --set-upstream-to=origin/main main
git add .
git commit -m "Initial commit"
git push -u origin main
Reverting History
// History: v1 --> v2 --> v3
// reset: Move HEAD pointer back (destructive)
git reset --hard HEAD~1 // Move back 1 commit (HEAD^, HEAD~1, HEAD~10 etc.)
git reset --hard <commit_id> // Jump to specific hash (first 6-7 chars suffice)
git push -f // Force push required after reset
// revert: Create a new commit that undoes changes (non-destructive)
// Example: Removing changes from v2 creates v4
git revert -n <commit_id>
Comparing Versions
// Compare working directory with index (HEAD)
git diff HEAD -- src/login.py
// Compare two different commits
git diff HEAD HEAD^ -- src/login.py
// List only filenames changed between two commits
git diff 2da595c daea1d6 --name-only
Fetching and Merging
// git pull is equivalent to fetch followed by merge
git fetch origin main // Download remote data to local references
// Optional: git log -p main..origin/main // Inspect differences before merging
git merge origin/main // Integrate remote changes
Branch Integration Strategies
// Merge Strategy:
git checkout feature
git merge main
// Or single line:
git merge main feature
// Creates a merge commit preserving history from both branches.
// Safer operation as it does not alter existing branch history.
// Rebase Strategy:
git checkout feature
git rebase main // Use -i for interactive mode
// Moves the feature branch to the tip of main, replaying feature commits on top.
// Warning: Rewrites history. Use with caution if feature branch is shared.