Mastering Git: A Comprehensive Guide to Commonly Used Commands

1. Setting Up Git

Installing Git

  • To install Git, visit and download the appropriate version for your operating system.
  • Follow the installation instructions.

Configuring Git

  • Configure your name and email:
  git config --global "Your Name"
  git config --global "[email protected]"

2. Creating a New Repository

Initializing a Repository

  • To create a new Git repository in an existing directory, use:
  git init

Cloning a Repository

  • To clone a remote repository to your local machine:
  git clone <repository_url>

3. Basic Workflow

Checking the Status

  • To check the status of your working directory:
  git status

Adding Files

  • To stage files for commit:
  git add <file(s)>

Committing Changes

  • To commit staged changes with a message:
  git commit -m "Your commit message"

Viewing Commit History

  • To view the commit history:
  git log

4. Branching

Creating a New Branch

  • To create a new branch:
  git branch <branch_name>

Switching Branches

  • To switch to a different branch:
  git checkout <branch_name>

Merging Branches

  • To merge changes from one branch into another:
  git checkout <target_branch>
  git merge <source_branch>

Deleting Branches

  • To delete a branch (locally):
  git branch -d <branch_name>

5. Remote Repositories

Adding a Remote

  • To add a remote repository:
  git remote add <remote_name> <repository_url>

Pushing to a Remote

  • To push your local changes to a remote repository:
  git push <remote_name> <branch_name>

Pulling from a Remote

  • To pull changes from a remote repository:
  git pull <remote_name> <branch_name>

6. Collaboration

Forking a Repository

  • To fork a repository on GitHub, click the “Fork” button on the repository’s page.

Creating Pull Requests

  • After making changes in your forked repository, create a pull request to the original repository on GitHub.

Reviewing Pull Requests

  • Review and comment on pull requests in the original repository to collaborate with others.

7. Advanced Git Concepts

Stashing Changes

  • To temporarily save changes without committing:
  git stash

Resetting Commits

  • To reset the branch to a specific commit:
  git reset --hard <commit_hash>

Reverting Commits

  • To create a new commit that undoes a previous commit:
  git revert <commit_hash>

This guide covers essential Git commands for various scenarios. Git can be a complex tool, but mastering these commands will help you manage your version control efficiently.

Hello, I’m Anuj. I make and teach software.

My website is free of advertisements, affiliate links, tracking or analytics, sponsored posts, and paywalls.
Follow me on LinkedIn, X (twitter) to get timely updates when I post new articles.
My students are the reason this website exists, crafted with the affection and dedication they’ve shown. ❤️

Feedback Display