JustGeek.in Tech, simplified.

Git Command Examples

Before diving into Git command examples, let’s explore what Git is and why it’s essential.

What is Git?

Git is a distributed version control system designed to track changes in files, enabling collaboration among programmers during software development. It allows you to maintain multiple versions of a file efficiently, saving them in a log format.

Git is widely recognized for its speed, scalability, and robust set of features, making it a staple in modern software development workflows.

Key Benefits of Git

  • Free and Open Source: Git is available for anyone to use and modify.
  • Faster Performance: Optimized for speed, Git handles large repositories with ease.
  • Widely Used: Git is supported across various platforms and has an extensive community.

Git Commands

Below are some commonly used Git commands with practical examples:

1. Git Clone

Clone a repository to your local machine.

$ git clone <repository-url>

Example:

Cloning a public repo of Just Geek:

$ git clone https://github.com/justgeek-in/public-repo.git
Cloning into 'public-repo'...
remote: Enumerating objects: 35, done.
remote: Counting objects: 100% (35/35), done.
remote: Compressing objects: 100% (28/28), done.
remote: Total 35 (delta 7), reused 17 (delta 2), pack-reused 0
Unpacking objects: 100% (35/35), done.

2. Git Checkout

Switch to another branch or create a new one.

  • Switch to an existing branch:
$ git checkout <branch-name>
  • Create and switch to a new branch:
$ git checkout -b <new-branch-name>

3. Git Add

Stage changes for the next commit.

  • Add a specific file:
$ git add <file-path>
  • Add all files:
$ git add .

4. Git Commit

Record changes to the repository.

$ git commit -m "Your commit message"

5. Git Push

Push changes to the remote repository.

  • Push to the current branch:
$ git push
  • Push to a specific branch:
$ git push origin <branch-name>

6. Git Diff

View unstaged changes.

$ git diff

7. Compare Branches

Compare differences between two branches:

$ git diff <branch1> <branch2>

8. Git Status

Check the status of your working directory and staging area:

$ git status

9. Git Log

View commit history:

$ git log

10. Git Revert

Revert a specific commit:

  1. View the commit log:
$ git log
  1. Revert the commit:
$ git revert <commit-hash>
  1. Push the changes:
$ git push

Example:

$ git log
commit de3ff79d3424c76c80a993d38d92e388b924ac0a
Author: root <[email protected]>
Date:   Fri Aug 12 09:52:49 2022 -0400

    Adding test.sh

Revert the commit:

$ git revert de3ff79d3424c76c80a993d38d92e388b924ac0a
[master 78efb80] Revert "Adding test.sh"

Conclusion

These are some of the most commonly used Git commands to manage your repositories effectively. Understanding and mastering these commands will help streamline your development workflow.