Saturday, January 31, 2026

Git Basics Commands: Essential Commands

Git Basics Commands: Essential Commands Every Developer Must Know

Git Basics Commands: Essential Commands Every Developer Must Know

🎯 Learning Strategy: This guide covers the 20% of Git commands you'll use 80% of the time. Master these fundamentals before moving to advanced topics.

Repository Management Commands

Repository Basics

A Git repository (or repo) is a collection of files and their complete history. These commands help you create, clone, and manage repositories.

git init

Initializes a new Git repository in the current directory.

📌 Use when: Starting a new project from scratch

What happens: Creates a hidden .git directory containing all repository metadata.

Basic Usage
git init
git init -b main
Initialize with specific branch name (sets default branch to main)
git init --bare
Initialize in bare mode (for central repositories/servers)
git init --quiet
Initialize without verbose output
git clone

Creates a local copy of an existing remote repository.

📌 Use when: Working with existing projects from GitHub, GitLab, etc.

What happens: Downloads entire repository including all history and branches.

Basic Usage
git clone https://github.com/user/repository.git
git clone repo-url project-name
Clone repository into a specific directory name
git clone -b develop repo-url
Clone specific branch only (not the default branch)
git clone --depth 1 repo-url
Shallow clone (only recent history, saves disk space)
git clone --recursive repo-url
Clone repository with all submodules
🎮 Practice Exercise 1:
1. Create a new directory: mkdir practice-git
2. Navigate into it: cd practice-git
3. Initialize Git: git init
4. Verify with: ls -la (should see .git folder)
💡 Pro Tip: Use git init when starting new projects from scratch. Use git clone when you want to contribute to or use existing projects. Most beginners start by cloning repositories to learn from existing code.

git status: Your Git Dashboard

Understanding Repository State

git status is your most frequently used Git command. It shows the current state of your working directory and staging area.

Basic Usage
git status

Common git status Output Scenarios

Clean Working Directory
On branch main Your branch is up to date with 'origin/main'. nothing to commit, working tree clean
Untracked Files Present
On branch main Untracked files: (use "git add <file>..." to include in what will be committed) newfile.txt config.yml nothing added to commit but untracked files present
Modified Files Not Staged
On branch main Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: README.md modified: src/index.js no changes added to commit
Files Ready to Commit
On branch main Changes to be committed: (use "git restore --staged <file>..." to unstage) new file: script.js modified: index.html deleted: oldfile.txt
git status -s
Short status format (compact output with status codes)
git status -sb
Short status with branch information
git status --ignored
Show ignored files in output
git status -uno
Ignore untracked files in output (cleaner view)
✅ Best Practice: Run git status before and after every Git command. It helps you understand what's happening and prevents mistakes. Make it a habit - it's the Git equivalent of looking both ways before crossing.

Core Workflow Commands: Add & Commit

The Git Workflow Cycle

Files move through three states: Working Directory → Staging Area → Repository. git add moves files from working directory to staging area. git commit moves files from staging area to repository.

git add: Staging Changes

Moves changes from working directory to staging area.

Basic Usage
git add filename.txt
git add .
Stage all changes in current directory and subdirectories
git add -u
Stage all tracked files (modified/deleted only)
git add -A
Stage all files (new + modified + deleted)
git add *.js
Stage all JavaScript files using wildcard
git add -p
Interactive staging (review each change)
git add --no-ignore-removal
Stage removed files as well
git commit: Saving Snapshots

Creates permanent snapshot of staged changes.

Basic Usage
git commit -m "Add login functionality"
git commit -am "Quick update"
Stage all tracked files and commit (skip git add)
git commit --amend
Modify the most recent commit (change message or add files)
git commit --no-verify
Skip pre-commit and commit-msg hooks
git commit --allow-empty
Create empty commit (useful for CI/CD triggers)
git commit -v
Show diff in commit message editor
git commit --dry-run
Show what would be committed without actually committing
⚠️ Important Note about git commit -am:
git commit -am only stages and commits tracked files. It will NOT stage new (untracked) files. Use git add . first for new files. Also, the -am flag only works when you already have tracked files with changes.

Commit Message Guidelines

📝 Effective Commit Message Format:
1. Subject line (50 chars max): Imperative mood
2. Blank line: Separates subject from body
3. Body (72 chars per line): Explain WHY, not what
4. Footer: Reference issues, breaking changes
# Example of good commit message structure Add user profile picture upload - Implement file validation for jpg, png formats - Add progress bar for upload feedback - Create responsive image cropper component - Handle file size limit (max 5MB) Fixes #123 Related to #456
🎮 Practice Exercise 2:
1. Create a file: echo "# My Project" > README.md
2. Check status: git status
3. Stage file: git add README.md
4. Check status again: git status
5. Commit: git commit -m "Add project README"
6. View history: git log --oneline

Viewing History & Differences

Inspecting Changes

git log shows commit history, while git diff and git show help you examine specific changes in detail.

git log: Viewing History

Displays commit history with various formatting options.

Basic Usage
git log
git log --oneline
One line per commit (compact view)
git log --graph --all --oneline
Graph visualization with all branches
git log -10
Show last 10 commits only
git log -p
Show patch (diff) for each commit
git log --stat
Show statistics (files changed, insertions/deletions)
git log --since="2024-01-01"
Show commits since specific date
git log --grep="bug"
Search commits containing "bug" in message
git log --author="John"
Show commits by specific author
git diff: Comparing Changes

Shows differences between files, commits, or branches.

Basic Usage
git diff
git diff --staged
Compare staged changes with last commit
git diff HEAD~3
Compare with 3 commits ago
git diff main..feature
Compare two branches
git diff --name-only
Show only file names, not content
git diff --word-diff
Word-level differences (easier to read)
git diff --cached
Alias for --staged (older Git versions)
git diff HEAD
Compare working directory with last commit
git diff abc123 def456 -- README.md
Compare specific file between two commits
git show: Examining Commits

Displays detailed information about specific commits.

Basic Usage
git show abc123def
git show HEAD
Show latest commit details
git show --stat
Show statistics only (files changed count)
git show --name-only
Show only file names in commit
git show abc123:README.md
Show specific file version from commit
git show --pretty=fuller
Show detailed commit information
git show HEAD~2:src/
Show directory contents from 2 commits ago
🔍 Debugging Tip: Use git diff to see what you're about to commit. Use git log -p to find when a bug was introduced. Use git show to examine specific suspicious commits.

.gitignore & .gitkeep Files

Controlling What Git Tracks

.gitignore tells Git which files to ignore (not track). .gitkeep is a convention to track empty directories.

Creating .gitignore

Create and manage files to exclude from version control.

Basic Usage
touch .gitignore
echo "*.log" >> .gitignore
Add pattern to ignore all log files
git check-ignore -v filename
Check why a file is being ignored
git ls-files --others --ignored
List all ignored files
git rm --cached filename
Remove file from Git but keep locally
.gitkeep Usage

Tracking empty directories in Git (convention, not command).

Creating Empty Directories
mkdir -p logs images uploads touch logs/.gitkeep images/.gitkeep uploads/.gitkeep
git add logs/.gitkeep
Stage .gitkeep file to track directory
echo "*" > dir/.gitignore
Alternative: create .gitignore to keep directory
echo "!.gitignore" >> dir/.gitignore
Add exception to keep .gitignore file itself
find . -name ".gitkeep" -type f
Find all .gitkeep files in project

Common .gitignore Patterns

# ========================================== # COMMON .gitignore PATTERNS # ========================================== # Operating system files .DS_Store Thumbs.db desktop.ini *.swp *.swo *~ # IDE and editor files .vscode/ .idea/ *.swp *.swo *.sublime-* # Dependency directories node_modules/ vendor/ __pycache__/ *.pyc *.pyo .pytest_cache/ # Build outputs dist/ build/ *.exe *.dll *.so *.dylib # Environment variables .env .env.local .env.development.local .env.test.local .env.production.local .secrets # Logs and databases *.log npm-debug.log* yarn-debug.log* yarn-error.log* *.sqlite *.db # Temporary files *.tmp *.temp temp/ tmp/ # Coverage reports coverage/ *.lcov htmlcov/ # Package manager files package-lock.json yarn.lock pnpm-lock.yaml
⚠️ Important: .gitignore only affects untracked files. If you've already committed a file, adding it to .gitignore won't remove it from Git. Use git rm --cached filename to stop tracking previously committed files.

.gitignore Pattern Syntax

Pattern Meaning Example
*.log All files ending with .log app.log, error.log
temp/ Entire directory and its contents temp/file.txt, temp/sub/file.txt
!important.log Exception (don't ignore this file) important.log (kept, others ignored)
/debug.log Only at root level, not subdirectories debug.log (root), not src/debug.log
debug/*.log All .log files in debug directory debug/app.log, debug/error.log
debug/**/*.log All .log files in debug and subdirectories debug/file.log, debug/sub/file.log
🎮 Practice Exercise 3:
1. Create .gitignore: touch .gitignore
2. Add patterns: echo "*.log\nnode_modules/\n.env" > .gitignore
3. Create empty directory: mkdir data
4. Add .gitkeep: touch data/.gitkeep
5. Stage and commit: git add . && git commit -m "Add .gitignore and directories"

Git Basics Cheat Sheet

Quick Reference Guide

Copy and keep this cheat sheet handy while you're learning Git.

Repository Setup
git init
Initialize new repository
git clone [url]
Clone existing repository
git remote add origin [url]
Add remote repository
Status & Info
git status
Check repository status
git status -s
Short status format
git log --oneline
Compact commit history
Basic Workflow
git add [file]
Stage specific file
git add .
Stage all changes
git commit -m "[msg]"
Commit staged changes
git commit -am "[msg]"
Stage tracked files and commit
Viewing Changes
git diff
Show unstaged changes
git diff --staged
Show staged changes
git show
Show latest commit
git log -p
History with changes

Common Workflow Patterns

Daily Development Workflow
git status # Check current state git add . # Stage all changes git commit -m "Description" # Commit changes git push # Push to remote
Careful Review Workflow
git status # Check what changed git diff # Review unstaged changes git add -p # Interactively stage changes git diff --staged # Review staged changes git commit # Commit with editor
Debugging & Investigation
git log --oneline -20 # Recent commits git show [commit-hash] # Examine specific commit git diff [hash1] [hash2] # Compare two commits git blame filename # Who changed what line
🚀 Next Steps: Once you've mastered these basic commands, learn: 1. Branching (git branch, git checkout, git merge)
2. Remote operations (git push, git pull, git fetch)
3. Undoing changes (git reset, git revert, git restore)
4. Stashing (git stash) for temporary saves
💪 Keep Practicing: The key to Git mastery is regular practice. Use these commands daily. Make mistakes in a practice repository. Try breaking things and fixing them. Every expert was once a beginner!

No comments:

Post a Comment

Git Basics Commands: Essential Commands

Git Basics Commands: Essential Commands Every Developer Must Know Git Basics Commands: Essential Commands Every Develop...