Dec 30, 2024

Essential Git Commands: A Quick Guide

Essential Git Commands: A Quick Guide

Essential Git Commands: A Quick Guide

Yellow Flower
Yellow Flower

Git Commands: A Quick Guide

Git is a powerful version control system used for tracking changes in code. This guide provides a concise overview of key Git commands for initializing repositories, tracking changes, and managing versions.


1. Initialize a Repository

  • Create an empty repository in a new directory:
    git init repo_name

  • Create a repository in the current working directory (cwd):
    git init

2. Check Repository Status

  • View untracked files and pending commits:
    git status

3. Stage Files for Commit

  • Add all files and folders to staging:
    git add .

  • Add a specific file to staging:
    git add filename.txt

4. Commit Changes

  • Commit with a message:
    git commit -m "Commit message here"

5. View Commit History

  • List all commits in reverse order:
    git log

  • Limit the number of commits displayed:
    git log -4

  • Filter by file:
    git log filename.txt

  • Filter by date range:
    git log --since='2024-04-02' --until='2024-05-03'

6. Show Specific Commit Details

  • Display details of a specific commit:
    git show commit_hash

7. Compare Changes

  • Compare a file with its last committed version:
    git diff filename.txt

  • Compare staged changes:
    git diff --staged filename.txt

  • Compare two commits:
    git diff commit1 commit2

  • Compare the last commit with the previous one:
    git diff HEAD~1 HEAD

8. Revert Changes

  • Revert to the latest commit:
    git revert HEAD

  • Revert to the previous commit:
    git revert HEAD~1

  • Skip opening the editor for a message:
    git revert HEAD --no-edit

9. Restore Files

  • Restore a specific file to a previous version:
    git checkout HEAD~1 -- filename.txt

  • Unstage a file:
    git restore --staged filename.txt

  • Unstage all files:
    git restore --staged .

Conclusion

By mastering these essential Git commands, developers can efficiently manage their codebase, track changes, and collaborate effectively.