Mastering Git Commands

Published on January 4, 2024 1 min read 681 views

Navigating the world of Git can be daunting, but fear not! Let's explore essential commands with explanations and examples to demystify Git for you.

Understanding Git Basics

Git is a powerful version control system, and mastering its commands is crucial for efficient collaboration and code management.

1. Initializing a Repository:

To start tracking your project, use:


git init

This command initializes a new Git repository in your current project directory.

2. Cloning a Repository:

Clone an existing repository with:


git clone repository_url

Example: git clone https://github.com/example/repo.git

3. Basic Snapshotting:

Stage changes for commit:


git add file

Example: git add index.html

Commit changes:


git commit -m "Your commit message"

Example: git commit -m "Add new feature"

4. Branching:

Create a new branch:


git branch branch_name

Example: git branch feature-branch

Switch to a branch:


git checkout branch_name

Example: git checkout feature-branch

Create and switch to a new branch:


git checkout -b new_branch_name

Example: git checkout -b bug-fix

5. Merging:

Merge changes from one branch to another:


git merge branch_name

Example: git merge feature-branch

6. Remote Repositories:

Add a remote repository:


git remote add remote_name repository_url

Example: git remote add origin https://github.com/example/repo.git

Push changes to a remote repository:


git push remote_name branch_name

Example: git push origin main

7. Handling Conflicts:

Resolve merge conflicts manually or mark conflicts as resolved with:


git add file

Example: git add conflicted-file

8. Inspecting Changes:

View changes made but not yet committed:


git diff

View changes made in a specific commit:


git show commit_hash

9. Undoing Changes:

Discard changes in your working directory:


git checkout -- file

Example: git checkout -- index.html

Discard local changes in a specific commit:


git revert commit_hash

Example: git revert abc123

Reset to a specific commit:


git reset commit_hash

Example: git reset --hard xyz456

10. Git Log:

View commit history:


git log

Customize log output:


git log --pretty=format:"%h - %an, %ar : %s"

Conclusion

Mastering these Git commands will empower you to navigate version control efficiently. Refer to this guide and embrace the world of collaborative coding with confidence. Happy coding!