How Can You Move a Specific Commit to Another Branch? (Cherry Pick) #
- Cherry Pick – Apply One Commit from One Branch to Another: Use
git cherry-pick <commit-id>
to copy a specific commit into your current branch - Perfect for Isolating Important Fixes: If you fixed a bug in a feature branch along with other changes, cherry-pick lets you move just the bug fix to the integration branch
- Keeps Commit History Clean: Lets you move changes without mixing unrelated code
- Watch for Conflicts: If the code has changed in both branches, cherry-pick may cause a conflict — Git will ask you to resolve it
# View commits on other branch
git log feature-a --oneline
# SAMPLE OUTPUT:
# a1b2c3d Add footer section
# 4d5e6f7 Add subscription logic
# 8g9h0i1 Fix header layout
# Cherry Pick Specific Commit
git cherry-pick a1b2c3d
# WHAT: Applies only "Add footer section" commit to main
# WHY: You don't want the entire feature branch
# TIP: You can pick multiple commits
# git cherry-pick a1b2c3d 4d5e6f7
# If Git reports a conflict, fix it manually
# Then run:
git add .
git cherry-pick --continue
# To complete the cherry-pick process
# Push the Updated Main Branch
git push origin main
# Best Practice: Cherry-pick only tested, self-contained commits
How Can You Mark Important Milestones in Your Project? #
- Tags – Mark Important Milestones in Your Project: Git tags are like sticky notes that highlight specific points in your commit history
- Perfect for Versioning: Use tags to mark release points like
v1.0
,v2.0
— making it easy to reference stable versions of your code - Tags Don’t Move: Unlike branches, tags are fixed — they always point to the same commit
- Great for References: Tags make it easy to check out old versions or compare changes between releases
- Best Practice: Always use annotated tags for official releases — they provide helpful context in the history
# ------------------------------------
# STEP 1: Create a tag on a commit
# ------------------------------------
git tag v1.0
# WHAT: Creates a lightweight tag 'v1.0' on latest commit
# WHY: To mark important points like releases
# ------------------------------------
# STEP 2: Create an annotated tag (recommended)
# ------------------------------------
git tag -a v1.1 -m "Release version 1.1"
# WHAT: Annotated tag with message and metadata
# Includes author, date, and message
# ------------------------------------
# STEP 3: Push tag to remote
# ------------------------------------
git push origin v1.1
# WHAT: Shares the tag with collaborators
# ------------------------------------
# STEP 4: List tags
# ------------------------------------
git tag
# Lists all tags in the repository
# ------------------------------------
# STEP 5: Checkout a tag (read-only mode)
# ------------------------------------
git checkout v1.1
# WHAT: Moves to a detached HEAD at the tag
# ✅ Tip:
# To create a branch from tag:
# git switch -c bugfix v1.1
# ✅ Tag Use Cases:
# - Marking release versions
# - Identifying stable checkpoints
# - Used by CI/CD pipelines to trigger builds
How Can You Pause Your Work and Come Back Later Without Losing Anything? (Stash) #
- Stash – Temporarily Save Your Changes: Use
git stash
to save uncommitted changes without committing them, so you can switch branches freely - Clean Working Directory in Seconds: Stashing clears your changes from the working directory so you can focus on something else without losing work
- Come Back with git stash pop: Use
git stash pop
to restore your saved changes and continue exactly where you left off - Delete When Done: Use
git stash drop
to delete a specific stash orgit stash clear
to remove all at once
# You’re working on a new feature, but
# need to switch branches before finishing.
# ---
# STEP 1: Start with uncommitted changes
# ---
git checkout -b feature/navbar
# Make changes:
# - Edit index.html
# - Edit style.css
# Check current status
git status
# OUTPUT: Modified files (not yet committed)
# ---
# STEP 2: Save work using stash
# ---
git stash push -m "WIP: Add navbar layout"
# WHAT: Saves tracked changes with a label
# WHY: Easier to identify in stash list
# TIP: Preferred over older `git stash save` style
# VARIATION:
# git stash -u -m "WIP: Navbar with image"
# Also stashes untracked files
# ---
# STEP 3: Switch branches safely
# ---
git checkout main
# NOW: You’re free to fix something else!
# (e.g., make and commit a hotfix on main)
# ---
# STEP 4: Return to your work
# ---
git checkout feature/navbar
# List all stash entries
git stash list
# Shows:
# stash@{0}: On feature/navbar: WIP: Add navbar layout
# ---
# STEP 5: Apply the stash back
# ---
git stash apply stash@{0}
# WHAT: Applies changes, keeps stash entry
# USE WHEN: You might reuse the stash again
# VARIATION:
# git stash pop
# Applies and deletes stash entry immediately
# ---
# STEP 6: Remove stash entry manually
# ---
git stash drop stash@{0}
# OR remove all:
git stash clear
How Can You Keep Unwanted Files Out of Your Git Repository? #
- .gitignore – Tell Git What to Ignore: The
.gitignore
file lets you specify which files or folders Git should not track - Avoid Committing Unnecessary Files: Helps prevent accidental commits of files like logs, build outputs, temp files, or IDE configs
- Simple Patterns for Powerful Control: You can ignore by file name (
.env
), file type (*.log
), or folder (/node_modules/
) - Can Be Shared Across Teams: Commit the
.gitignore
file to your repo so everyone follows the same ignore rules - Best Practice: Add
.gitignore
early in the project — before committing files you don’t want tracked
-
Creating a
.gitignore
File:touch .gitignore
-
Common Patterns:
# Ignore specific files secrets.txt # Ignore file types *.log *.tmp # Ignore directories node_modules/ dist/
Scenario: How to Quickly Find the Commit That Introduced a Bug in Git #
- Git Bisect – Find the Bug Faster:
git bisect
helps you locate the exact commit that introduced a bug using binary search — much faster than checking every commit manually - (Step 1) Start the Bisect Session: Run
git bisect start
to begin the binary search for the buggy commit - (Step 2) Mark the Bad Commit: Use
git bisect bad <latest-commit>
— this is the commit where the bug is confirmed - (Step 3) Mark the Good Commit: Use
git bisect good <oldest-working-commit>
— this is where everything was working fine - (Step 4) Git Picks a Middle Commit Automatically: Git checks out a commit halfway between good and bad
- (Step 5) Test and Report the Result: Run the app or tests.
- If it’s broken, run
git bisect bad
- If it’s fine, run
git bisect good
- Git will narrow down further
- If it’s broken, run
- (Step 6) Repeat Until Buggy Commit Is Found: Git keeps halving the search space, you’ll find the exact commit
- (Step 7) Reset After Investigation: Use
git bisect reset
to return to your original branch once the culprit commit is found - Binary Search in Action: Saves massive time by testing only 5-6 commits instead of all 25
Scenario: How Can You Create Git Shortcuts to Save Time and Type Less? #
- Aliases – Create Shortcuts for Git Commands: Git aliases let you define custom shortcuts for long or frequently used commands
- Save Time and Avoid Typos: Instead of typing
git commit -m
, you can definegit cm
as a quick alias - Define Once, Use Everywhere: Set aliases using
git config --global
so they work in all your Git projects
# ------------------------------------
# Git Aliases - Make Git Commands Shorter
# ------------------------------------
# STATUS
git config --global alias.st status
# git st → git status
# ADD & COMMIT
git config --global alias.cm "commit -m"
# git cm "message" → git commit -m "message"
# LOG - Pretty One-Liner
git config --global alias.lg "log --oneline --graph --all"
# git lg → visual commit history
# BRANCH
git config --global alias.br branch
# git br → git branch
# CHECKOUT
git config --global alias.co checkout
# git co main → git checkout main
# DIFFERENCE
git config --global alias.df diff
# git df → git diff
# 🔁 Add `--global` for all repos
How Can You Customize Git to Work the Way You Want? #
- Git Config – Control How Git Behaves:
git config
lets you view and set Git settings that affect how Git works across projects or on your machine - Settings Are Saved: Global Configuration is saved in
~/.gitconfig
, Repo specific configuration is stored in<repo>/.git/config
# ------------------------------------
# Global Git Configuration
# Applies to all repos for current user
# ------------------------------------
git config --global user.name "Ranga Rao"
git config --global user.email "[email protected]"
# Sets your identity for commits
git config --global init.defaultBranch main
# Sets 'main' as the default branch for new repos
git config --global core.editor "code --wait"
# Sets VS Code as default Git editor
git config --global color.ui auto
# Enables colored output for better readability
git config --global alias.st status
# Creates a shortcut: git st → git status
# ------------------------------------
# View Config Settings
# ------------------------------------
git config --list --global
# Lists all global settings
# ------------------------------------
# Local Config (Per Repo)
# ------------------------------------
# cd INTO THE REPO
git config user.name "Ranga (in28minutes)"
git config user.email "[email protected]"
# Overrides global settings for just this repo
# ✅ Use Cases:
# - Set identity, editor, aliases
# - Customize behavior globally or locally
# - Supports team conventions and tools
How Do You Enforce Commit Message Standards Using Git Hooks? #
- Automatic Quality Control: Git hooks act like bouncers that validate commit messages before they enter your repo
- Team Consistency: Ensures everyone follows the same standards without manual checking
- Better Documentation: Makes commit history more readable and useful for the whole team
# --------------------------------------------
# Enforce Commit Message Standard Using a Hook
# --------------------------------------------
# STEP 1: Go to your Git repo's .git/hooks folder
cd my-repo/.git/hooks
# STEP 2: Create or modify 'commit-msg' file
touch commit-msg
chmod +x commit-msg # Make it executable
# STEP 3: Add validation logic
# Enforces: Commit msg must start with a capital letter
# and be at least 10 characters long
nano commit-msg
# Paste the following:
#!/bin/sh
msg=$(cat "$1")
if ! echo "$msg" | grep -Eq "^[A-Z].{9,}"; then
echo "❌ Commit message must:"
echo " - Start with a capital letter"
echo " - Be at least 10 characters"
exit 1
fi
# STEP 4: Try a bad commit and see it fail
# git commit -m "bad message" → ❌ rejected
# ✅ Great for enforcing consistency across teams!
# 🧪 You can write complex rules using regex or shell
There are a variety of hooks possible:
Hook | When It Runs |
---|---|
pre-commit |
Before git commit is run |
prepare-commit-msg |
Before editor opens with default commit msg |
commit-msg |
After message is entered but before commit |
post-commit |
After a successful commit |
pre-push |
Before git push is run |
post-merge |
After a successful merge |
post-checkout |
After switching branches |
Give Examples of a Few Useful Git Commands #
Command | What It Does | Key Options / Details |
---|---|---|
git log | Shows commit history for the current branch | --abbrev-commit : short commit IDs--pretty : custom format for commits--oneline : one commit per line--all : show all branches--graph : ASCII graph showing branching |
git diff | Compares changes between areas in the repo | Default: Working Directory vs Index--cached or --staged : Index vs Last Commit (Local DB)git diff <commit1> <commit2><br>git diff <file-path> |
git restore |
Restores file from index to working directory | Discards unstaged changes |
git restore --staged |
Restores file from last commit to index only | Unstages a file, but keeps working directory unchanged |
git rm |
Removes file from working directory and index | To keep file locally but stop tracking: git rm --cached |
git revert |
Creates a commit that reverses a previous commit | Used to safely undo commits without rewriting history |
git pull | Fetches from remote and merges into current branch | Two steps in one:fetch : Remote → Local DBmerge : Local DB → Index → Working Directory |
git blame |
Shows who made each change in a file and when | Helps trace the origin of specific lines |
git grep |
Searches for text patterns in tracked files | Faster than regular grep |