Fundamentals 21 min read

Essential Git Commands Cheat Sheet for Every Scenario

This comprehensive Git manual walks you through initialization, daily workflow, branch management, remote operations, tag handling, undo/recovery, stash usage, advanced features like LFS and submodules, collaboration workflows, performance tuning, common pitfalls, shortcut aliases, core principles, and recommended version upgrades, providing concrete commands, examples, and best‑practice guidelines.

CodeSmart Hoops
CodeSmart Hoops
CodeSmart Hoops
Essential Git Commands Cheat Sheet for Every Scenario

Case First

Tags: Git, push, pull, rebase, merge

Problem description : Remote push rejected.

Cause analysis : Local branch is behind the remote branch; a forced push would overwrite remote history, so the server rejects the request.

Solution

Option 1 – Pull then push (recommended)

Option 2 – Force push (use with caution)

1. Initialization and Configuration

1.1 Repository initialization

git init                     # Initialize a new repository
git clone <url>              # Clone a remote repository
git clone <url> <dir>        # Clone into a specific directory

1.2 User configuration

git config --global user.name "Your Name"      # Set user name
git config --global user.email "[email protected]" # Set email
git config --global core.editor "vim"        # Set editor
git config --list                              # List all configs
git config --global --unset <key>              # Remove a config

2. Daily Development Workflow

2.1 View status

git status                     # Show working tree status
git status -s                  # Short format
git log                        # Show commit history
git log --oneline              # One‑line summary
git log --graph --all          # Graphical branch view
git log -p                     # Show diffs per commit
git log --author="name"       # Filter by author
git log --since="2 weeks ago" # Filter by date
git diff                       # Unstaged changes
git diff --staged              # Staged changes
git diff HEAD~1                # Compare with previous commit

2.2 File operations

git add <file>                 # Add file to staging area
git add .                      # Add all changes
git add -p                     # Interactive add
git rm <file>                  # Delete file
git rm --cached <file>         # Remove from index, keep file
git mv <old> <new>             # Rename or move file
git checkout -- <file>         # Discard working‑tree changes
git restore <file>            # Newer command (Git 2.23+)

2.3 Commit code

git commit -m "message"               # Commit with message
git commit -am "message"              # Add tracked files then commit
git commit --amend                    # Amend last commit
git commit --amend -m "msg"          # Amend message
git reset HEAD~1                       # Undo last commit, keep changes
git reset --hard HEAD~1                # Undo commit and discard changes
git revert <commit>                    # Create a reverse commit (safe for pushed commits)

3. Branch Management

3.1 Basic operations

git branch                         # List local branches
git branch -a                      # List all branches (including remote)
git branch <name>                  # Create branch
git branch -d <name>               # Delete merged branch
git branch -D <name>               # Force delete branch
git checkout <branch>             # Switch branch
git switch <branch>               # Newer switch command (Git 2.23+)
git checkout -b <name>            # Create and switch
git switch -c <name>               # Newer create‑and‑switch
git merge <branch>                # Merge into current branch

3.2 Merge strategies

git merge --no-ff <branch>          # Disable fast‑forward, create merge commit
git merge --squash <branch>        # Squash merge into a single commit
git rebase <branch>                # Rebase onto target branch
git rebase -i HEAD~3               # Interactive rebase for editing commits

3.3 Conflict resolution

git mergetool                     # Launch graphical merge tool
git diff --ours                   # Show our version
git diff --theirs                 # Show their version
git checkout --ours <file>        # Keep our version
git checkout --theirs <file>      # Keep their version
git add <resolved-files>          # Mark conflicts resolved
git rebase --continue             # Continue rebase
git rebase --abort                # Abort rebase

4. Remote Repository Operations

4.1 Remote management

git remote -v                     # Show remote URLs
git remote add origin <url>        # Add remote
git remote remove <name>          # Remove remote
git remote set-url origin <url>   # Change remote URL
git fetch origin                  # Fetch without merging
git pull origin <branch>          # Pull and merge
git pull --rebase origin <branch> # Pull and rebase
git push origin <branch>          # Push
git push -u origin <branch>       # Push and set upstream
git push --force-with-lease       # Safe force push
git push --delete origin <branch> # Delete remote branch

4.2 Non‑fast‑forward error handling

# Recommended: pull then push
git pull --rebase origin master
git push origin master

# Cautious: force push
git push --force-with-lease origin master

# Inspect differences before deciding
git fetch origin
git log HEAD..origin/master   # What remote has extra
git log origin/master..HEAD   # What we have extra

5. Tag Management

git tag                         # List tags
git tag -l "v1.*"               # Fuzzy search
git tag v1.0.0                  # Create lightweight tag
git tag -a v1.0.0 -m "msg"      # Create annotated tag
git show v1.0.0                # Show tag details
git push origin v1.0.0          # Push single tag
git push origin --tags          # Push all tags
git tag -d v1.0.0               # Delete local tag
git push origin :refs/tags/v1.0.0 # Delete remote tag

6. Undo and Recovery

6.1 Working‑tree undo

git checkout -- <file>          # Discard changes
git restore <file>              # Newer command
git clean -f                     # Delete untracked files
git clean -fd                    # Delete untracked files and directories
git clean -n                     # Preview deletions

6.2 Staging‑area undo

git reset HEAD <file>            # Unstage file
git restore --staged <file>     # Newer command
git reset HEAD                   # Clear staging area

6.3 Commit undo

git commit --amend               # Amend last commit
git reset --soft HEAD~1        # Undo commit, keep staged changes
git reset HEAD~1                 # Undo commit, keep working changes
git reset --hard HEAD~1        # Undo commit and discard all changes
git revert <commit>              # Create reverse commit (safe for pushed commits)

6.4 Recover deleted files

git reflog                      # Show all reference logs
git reset --hard <commit-id>    # Restore to specific commit
git cherry-pick <commit-id>     # Pick a specific commit

7. Stash (Temporary Storage)

git stash                       # Save current changes
git stash save "msg"            # Save with message
git stash list                  # List stashes
git stash pop                   # Apply latest stash and drop it
git stash apply stash@{0}       # Apply specific stash without dropping
git stash drop stash@{0}         # Delete specific stash
git stash clear                 # Remove all stashes
git stash branch <name>         # Create branch from stash

8. Advanced Operations

8.1 Search and filter

git log --grep="keyword"        # Search commit messages
git log -S "code"               # Search code changes
git blame <file>                 # Show last author per line
git bisect start                 # Start binary search for bug
git bisect bad                   # Mark current as bad
git bisect good                  # Mark current as good
git bisect reset                 # End bisect

8.2 Submodules

git submodule add <url>          # Add submodule
git submodule update --init     # Init and update
git submodule update --remote    # Update to latest upstream

8.3 Large File Handling (Git LFS)

git lfs install                 # Install LFS
git lfs track "*.psd"           # Track specific file types
git lfs ls-files                # List LFS‑tracked files

8.4 Archive and pack

git archive -o latest.zip HEAD  # Export as zip
git archive -o latest.tar HEAD  # Export as tar

9. Collaboration Workflow

9.1 Fork workflow

git remote add upstream <original-url> # Add upstream repo
git fetch upstream                     # Get upstream updates
git merge upstream/master               # Merge upstream changes
git push origin master                  # Push to your fork

9.2 Code review process

git fetch origin pull/<ID>/head:<branch> # Download PR branch
git cherry-pick <commit>                # Pick specific commit
git format-patch -1 HEAD                # Create patch file
git am <patch-file>                     # Apply patch

10. Performance Optimization and Maintenance

git gc                         # Garbage collection
git fsck                       # Verify repository integrity
git prune                      # Remove unreachable objects
git repack                     # Repack objects
git count-objects -v           # Show repository statistics

11. Common Issues Quick Reference

11.1 .gitignore examples

# Log files
*.log

# Dependency directories
node_modules/
target/
vendor/

# IDE configs
.idea/
.vscode/
*.iml

# System files
.DS_Store
Thumbs.db

# Build outputs
dist/
build/

# Environment files
.env
.env.local

# Keep empty directories
!.gitkeep

11.2 Change commit author

# Amend last commit author
git commit --amend --author="Name <email>"

# Bulk rewrite history author
git filter-branch --env-filter '
export GIT_AUTHOR_NAME="New Name"
export GIT_AUTHOR_EMAIL="[email protected]"
' -- --all

11.3 Find large files

git rev-list --objects --all | sort -k 2 > all_files.txt
git cat-file --batch-check < all_files.txt | sort -k 3 -n -r | head

11.4 Common error handling

# fatal: refusing to merge unrelated histories
git pull origin master --allow-unrelated-histories

# error: Your local changes would be overwritten by merge
git stash
git pull
git stash pop

# fatal: remote origin already exists
git remote set-url origin <new-url>

12. Shortcut Alias Configuration

# Basic aliases
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit

# Log aliases
git config --global alias.lg "log --oneline --graph --all"
git config --global alias.hist "log --pretty=format:'%h %ad | %s%d [%an]' --graph --all"

# Undo aliases
git config --global alias.undo "reset --soft HEAD~1"
git config --global alias.amend "commit --amend"

# Push aliases
git config --global alias.ps "push"
git config --global alias.pl "pull"

# List aliases
git config --get-regexp alias

Core Principles

Golden Rules

Use revert for pushed commits and reset for unpushed commits. revert creates a new reverse commit without rewriting history; reset rewrites history and should only be used locally before push.

Prefer pull --rebase to keep history linear. Avoids unnecessary merge commits and results in a cleaner, more readable history.

Never force‑push without confirming no collaborators are affected. Use --force-with-lease instead of --force; force‑push can overwrite others' work.

Run reflog before risky operations to create a recovery point. git reflog records all actions and serves as a last‑resort safety net; note the current commit ID before destructive commands.

Dangerous Operations List

git reset --hard

– discards uncommitted changes. git push --force – overwrites remote commits. git clean -fd – deletes untracked files and directories. git filter-branch – rewrites history. git gc --prune=now – immediately removes all dangling objects.

Best Practices

Commit discipline

Make small, frequent commits.

Write clear commit messages.

Each commit should address a single concern.

Branch strategy master/main: production code. develop: main development branch. feature/*: feature branches. hotfix/*: urgent fixes. release/*: release preparation.

Collaboration etiquette

Pull before pushing.

Avoid rewriting history on shared branches.

Delete merged branches promptly.

Perform code review before merging.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

workflowgitBest Practicescommand-lineversion controlgit-lfsgit-mergegit-rebase
CodeSmart Hoops
Written by

CodeSmart Hoops

A working programmer who loves coding and basketball. By day I debug code; by night I dissect tactics. I write articles to document my journey, focusing on Java, AI, Python and other programming topics, with occasional posts about basketball, English, and books. Hope it's helpful—thanks for following and support.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.