Mastering Git: 100+ Commands with Real-Time Examples

Introduction

Git is a powerful version control system used to manage code, collaborate on projects, and maintain project history. In this blog, we’ll explore over 100 Git commands categorized and explained with real-world examples.


Basic Setup

  1. git init: Initialize a new Git repository.
    Example:

     git init
    

    Creates a .git folder in the directory.

  2. git config: Configure user details or preferences.
    Example:

     git config --global user.name "Your Name"
     git config --global user.email "your-email@example.com"
    
  3. git clone: Clone an existing repository.
    Example:

     git clone https://github.com/user/repo.git
    

Branching and Merging

  1. git branch: Manage branches.
    Example:

     git branch feature-branch    # Create
     git branch                   # List
     git branch -d feature-branch # Delete
    
  2. git checkout: Switch branches or commits.
    Example:

     git checkout main
     git checkout <commit-hash>
    
  3. git switch: Another way to switch branches.
    Example:

     git switch feature-branch
    
  4. git merge: Merge branches.
    Example:

     git merge feature-branch
    
  5. git rebase: Reapply commits onto a new base branch.
    Example:

     git rebase main
    
  6. git rebase --interactive: Edit, squash, or reorder commits interactively.
    Example:

     git rebase -i HEAD~3
    

Staging and Committing

  1. git add: Stage changes.
    Example:

    git add file.txt
    git add .    # Stage all changes
    
  2. git commit: Save changes to the repository.
    Example:

    git commit -m "Initial commit"
    
  3. git commit --amend: Edit the last commit.
    Example:

    git commit --amend -m "Updated commit message"
    

Undoing Changes

  1. git reset: Undo commits or changes.
    Example:

    git reset --soft HEAD~1   # Undo commit, keep changes staged
    git reset --hard HEAD~1   # Undo commit and discard changes
    
  2. git revert: Create a new commit to reverse changes.
    Example:

    git revert <commit-hash>
    
  3. git clean: Remove untracked files.
    Example:

    git clean -f
    
  4. git stash: Save uncommitted changes temporarily.
    Example:

    git stash
    git stash pop    # Apply and remove stash
    

Viewing History

  1. git log: View commit history.
    Example:

    git log --oneline
    
  2. git reflog: View all HEAD changes.
    Example:

    git reflog
    
  3. git blame: Find who made changes to each line of a file.
    Example:

    git blame file.txt
    
  4. git show: Display changes in a specific commit.
    Example:

    git show <commit-hash>
    

Collaboration

  1. git fetch: Download updates from a remote repository.
    Example:

    git fetch
    
  2. git pull: Fetch and merge updates.
    Example:

    git pull origin main
    
  3. git push: Upload commits to a remote repository.
    Example:

    git push origin feature-branch
    
  4. git remote: Manage remote repositories.
    Example:

    git remote add origin https://github.com/user/repo.git
    

Advanced Commands

  1. git cherry-pick: Apply a specific commit to the current branch.
    Example:

    git cherry-pick <commit-hash>
    
  2. git bisect: Find a bug by binary searching through commits.
    Example:

    git bisect start
    git bisect bad
    git bisect good
    
  3. git tag: Add tags to commits.
    Example:

    git tag v1.0.0
    git push --tags
    
  4. git archive: Create an archive of repository files.
    Example:

    git archive --format=zip HEAD > repo.zip
    

Patch Management

  1. git format-patch: Generate patch files from commits.
    Example:

    git format-patch HEAD~3
    
  2. git apply: Apply a patch file.
    Example:

    git apply patch-file.patch
    

Cleanup

  1. git gc: Clean up unnecessary files.
    Example:

    git gc
    
  2. git prune: Remove unreachable objects.
    Example:

    git prune
    
  3. git clean: Remove untracked files and directories.
    Example:

    git clean -fd
    

Aliases and Shortcuts

  1. git alias: Create custom shortcuts.
    Example:

    git config --global alias.co checkout
    
  2. git config --edit: Edit Git configurations.
    Example:

    git config --edit
    

Submodules

Git submodules allow you to manage repositories as subdirectories inside another Git repository. They are particularly useful for managing dependencies or reusable components.

  1. Add a submodule
  •     git submodule add https://github.com/example/repo.git
    

    Example: Adding a reusable library as a submodule.

    1. Initialize submodules
    git submodule init

Example: Prepares the local repository to use submodules.

  1. Update submodules
    git submodule update

Example: Updates the submodule to the latest commit in the parent repository.

  1. Deinitialize a submodule
    git submodule deinit path/to/submodule

Example: Removes the submodule from your working directory.


Hooks

Git hooks are scripts that are triggered by specific Git actions, allowing you to automate tasks.

  1. View hooks
  •     git hooks
    

    Example: List all available hooks in your repository.

    1. Commit-msg hook
    echo "Commit message validation" > .git/hooks/commit-msg
    chmod +x .git/hooks/commit-msg

Example: Validates the format of commit messages.

    1. Pre-commit hook
    echo "Code linting check" > .git/hooks/pre-commit
    chmod +x .git/hooks/pre-commit

Example: Runs a linter before committing code.


Security

Git provides tools to verify commits and tags to ensure their authenticity.

  1. View GPG signatures for commits
  •   git log --show-signature
    

    Example: Ensures the commit was made by a verified user.

    1. Verify a tag
    git tag -v v1.0.0

Example: Checks the GPG signature of a tag.


Worktrees

Worktrees allow you to work on multiple branches simultaneously in different directories.

  1. Add a worktree
  •   git worktree add ../feature-branch feature-branch
    

    Example: Create a separate working directory for a branch.

    1. Remove a worktree
    git worktree remove ../feature-branch

Example: Clean up a worktree when it's no longer needed.


Debugging

Debugging tools help diagnose issues in your repository.

  1. Check repository health
  •   git fsck
    

    Example: Identifies corrupt or missing objects.

    1. Verify a commit
    git verify-commit <commit-hash>

Example: Checks the integrity of a specific commit.

  1. Verify a tag
    git verify-tag <tag-name>

Example: Ensures a tag is valid and unaltered.


Ignoring Files

Use .gitignore to exclude files or directories from being tracked.

  • Example .gitignore file:

      # Ignore log files
      *.log
    
      # Ignore node_modules directory
      node_modules/
    

    Example: Prevent tracking of temporary or dependency files.


Backup and Restore

Backup and restore repositories using Git bundles.

  • Create a bundle

      git bundle create backup.bundle main
    

    Example: Creates a backup of the main branch.

  • Verify a bundle

      git bundle verify backup.bundle
    

    Example: Ensures the bundle is valid.

Collaboration (Code Review)

Use Git's diff tools to review changes effectively.

  • Word-level diff

      git diff --word-diff
    

    Example: Highlights changes at the word level.

  • Compare two commits

      git diff <commit1>..<commit2>
    

    Example: Shows the differences between two commits.

  • Show changed files only

      git diff --name-only
    

    Example: Lists files modified between commits.


Miscellaneous Commands

Other useful Git commands for specific tasks.

  • Archive a repository

      git archive --format=zip --output=repo.zip main
    

    Example: Creates a zip archive of the repository.

  • Sparse checkout

      git sparse-checkout set <folder>
    

    Example: Checks out only a specific folder.

  • Set default branch name

      git config --global init.defaultBranch main
    

    Example: Ensures all new repositories use main as the default branch.

  • View file tree of a commit

      git diff-tree --no-commit-id --name-only -r <commit-hash>
    

    Example: Displays the file structure of a commit.

  • List tracked files

      git ls-files
    

    Example: Lists all tracked files in the repository.


Git Help

Git has built-in help documentation for quick reference.

  • View all help topics

      git help -a
    

    Example: Lists all available Git commands.

  • View config help

      git help config
    

    Example: Displays detailed help for the config command.


Collaboration with CI/CD

Git integrates seamlessly with CI/CD workflows.

  • Tagging for releases

      git tag -a v1.0.0 -m "Release 1.0.0"
      git push origin v1.0.0
    

    Example: Tags a release and pushes it to the remote repository.

  • Squashing commits for cleaner history

      git rebase -i HEAD~3
    

    Example: Combines multiple commits into one for a cleaner history.

  • Force push for overrides

      git push --force
    

    Example: Overwrites remote changes (use with caution).