Git Cheatsheet

Everyday git commands for tracking changes to your code, Kubernetes manifests, and configuration files.

Table of Contents

Setup and Configuration

# Set your name and email for all repositories
git config --global user.name "Your Name"
git config --global user.email "you@example.com"

# View the current configuration
git config --list

# Set the default branch name for new repositories
git config --global init.defaultBranch main

Starting a Repository

# Initialize a new repository in the current directory
git init

# Clone an existing repository
git clone https://github.com/example/repo.git

# Clone only a specific branch
git clone -b develop https://github.com/example/repo.git

Staging and Committing

# Check the status of the working directory
git status

# Stage a specific file
git add path/to/file

# Stage all changed files
git add .

# Commit staged changes with a message
git commit -m "Add feature"

# Stage and commit all tracked file changes in one step
git commit -am "Update config"

# Amend the previous commit
git commit --amend

Branching and Merging

# List local branches
git branch

# Create a new branch
git branch feature-x

# Switch to an existing branch
git checkout feature-x

# Create and switch to a new branch in one step
git checkout -b feature-x

# Merge a branch into the current branch
git merge feature-x

# Delete a branch that has already been merged
git branch -d feature-x

Syncing with Remotes

# Show configured remotes
git remote -v

# Add a remote
git remote add origin https://github.com/example/repo.git

# Fetch changes without merging them
git fetch origin

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

# Push local commits to a remote branch
git push origin main

# Push a new branch and set it to track the remote
git push -u origin feature-x

Inspecting History

# View commit history
git log

# View a condensed, graphical one-line log
git log --oneline --graph --all

# Show the changes introduced by a commit
git show <commit-hash>

# Show changes between the working directory and the last commit
git diff

# Show who last modified each line of a file
git blame path/to/file

Undoing Changes

# Discard unstaged changes in a file
git checkout -- path/to/file

# Unstage a file without discarding its changes
git restore --staged path/to/file

# Revert a commit by creating a new commit that undoes it
git revert <commit-hash>

# Reset the current branch to a previous commit, keeping changes staged
git reset --soft <commit-hash>

# Reset the current branch to a previous commit, discarding changes
git reset --hard <commit-hash>

Stashing

# Save uncommitted changes for later
git stash

# List stashed changes
git stash list

# Reapply the most recent stash and remove it from the list
git stash pop

# Apply a stash without removing it from the list
git stash apply

# Discard a stash
git stash drop