Git Commands Cheat Sheet

Version control is an absolute prerequisite for modern software engineering. Git is the industry-standard distributed version control system, empowering developers to track source code history, collaborate across distributed teams, manage feature branches, and safely revert code changes.

This comprehensive, developer-focused Git Cheat Sheet covers essential command workflows ranging from repository initialization and staging to branching, merging, rebasing, and remote synchronization.

1. Setup and Repository Initialization

Configure your global Git identity and initialize or clone repositories.

C
# Configure global username and email
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

# Initialize a new local Git repository
git init

# Clone an existing remote repository
git clone https://github.com/username/repository.git

2. Staging and Committing Changes

Track modified files, view repository status, and record snapshots with commit messages.

C
# Check status of working tree and staged files
git status

# Stage specific files or all changes
git add index.js
git add .

# Commit staged changes with a descriptive message
git commit -m "feat: implement user authentication endpoint"

# Stage and commit tracked files in a single step
git commit -am "fix: resolve database connection timeout bug"

3. Branching and Merging

Isolate feature development and bug fixes using branches, then integrate them back into main lines.

C
# List all local and remote branches
git branch -a

# Create and switch to a new feature branch
git checkout -b feature/jwt-auth
# Or using modern git switch:
git switch -c feature/jwt-auth

# Switch back to main branch
git switch main

# Merge feature branch into current branch
git merge feature/jwt-auth

4. Remote Synchronization (push, pull, fetch)

Synchronize your local repository commits with remote servers like GitHub, GitLab, or Bitbucket.

C
# Add or inspect remote repositories
git remote add origin https://github.com/username/repo.git
git remote -v

# Fetch changes from remote without merging
git fetch origin

# Pull latest changes from remote branch and merge
git pull origin main

# Push local commits to remote repository
git push origin feature/jwt-auth

5. Undoing Changes and Resetting

Safely revert erroneous commits, unstage files, or discard uncommitted modifications.

C
# Unstage a file while keeping local changes intact
git reset HEAD filename.js

# Discard uncommitted changes in working directory
git checkout -- filename.js

# Soft reset last commit (keeps changes staged)
git reset --soft HEAD~1

# Hard reset (WARNING: Discards all uncommitted and unpushed changes)
git reset --hard HEAD~1

Conclusion

Keep this Git command reference cheat sheet handy to streamline your version control workflows, manage branching strategies, and collaborate efficiently on software engineering projects.