Post

Git Commands Cheatsheet

A hand-picked collection of essential Git CLI commands for daily workflow

Git Commands Cheatsheet

I recently switched IDEs and decided to rely more on the terminal. Here is a documentation of my most frequently used git commands.

1. Setup & Configuration

  • Initialize Repository
1
git init
  • Configure User (Per Repository) Useful when I need a different identity for a specific project.
1
2
git config user.name "My Name"
git config user.email "me@example.com"
  • Configure Remote URL Note: Use add if it’s a new remote, or set-url to change an existing one.
1
git remote set-url origin https://github.com/username/repo.git

2. The Daily Loop

  • Check Status
1
git status
  • Stage Changes
1
2
3
git add <file_path>
# Or stage everything
git add .
  • Commit
1
git commit -m "feat: my commit message"
  • View History
1
2
3
git log
# Pro tip: One-line view for cleaner history
git log --oneline

3. Syncing

  • Pull with Rebase Keeps my history clean by moving my local commits on top of the incoming changes.
1
git pull origin main --rebase
  • Push
1
git push origin main

4. Undo & Corrections

  • Undo Last Commit (Soft Reset) Undoes the last commit but keeps the changes staged (ready to be committed again).
1
git reset --soft HEAD~1
  • Restore Staged Files Un-stages files (removes them from the index) but keeps my changes.
1
git restore --staged .
  • Amend Last Commit Adds staged changes to the previous commit without changing the message.
1
git commit --amend --no-edit
  • Edit Last Commit Message Only for local commits that haven’t been pushed yet.
1
git commit --amend -m "new message"
  • Edit Older Commit Messages Opens an interactive editor. Change pick to reword next to the commit I want to fix.
1
2
# HEAD~2 means "the last 2 commits"
git rebase -i HEAD~2

Just like amend, never do this if you have already pushed these commits to a shared branch, as it rewrites history.

5. Patching (The Manual Move)

Sometimes I just need to move a commit physically (via email or file) without pushing.

  • Create Patch for a Single Commit

    1. Find the Commit Hash:
      1
      
      git log --oneline
      
    2. Create the .patch File: Once I have the commit hash (say it’s abc1234), use the following command to create a patch:
      1
      
      git format-patch -1 abc1234
      
  • Create Patch for Multiple Commits
    • Example: Get the last 3 commits
      1
      
      git format-patch -3
      
    • Example: Range from specific commit to HEAD
      1
      
      git format-patch abc1234..HEAD
      
  • Apply Patch
1
git apply git apply /path/to/file.patch

6. Branching

  • Create New Branch from Base Creates and switches to a new branch based on a specific existing branch (instead of the current HEAD).
1
2
3
git checkout -b <new_branch_name> <base_branch_name>
# Example: Create 'feature-login' starting from 'main'
git checkout -b feature-login main
This post is licensed under CC BY 4.0 by the author.