Git is a powerful distributed version control system that helps you track changes in your code, collaborate with others, and maintain a complete history of your project. This guide walks you through the essential Git commands and workflows to get you started with version control on Linux.

How to Use Git on Linux

  1. Step 1: Install Git

    Install Git using your Linux distribution's package manager.

    For Debian/Ubuntu-based systems:

    sudo apt update
    sudo apt install git

    For Fedora/RHEL-based systems:

    sudo yum install git
  2. Step 2: Configure Your Identity

    Set up your user name and email address. This information will be associated with your commits.

    git config --global user.name "Your Name"
    git config --global user.email "youremail@example.com"
  3. Step 3: Initialize a Repository

    Navigate to the directory where you want to start version controlling your project and initialize a new Git repository.

    git init
  4. Step 4: Add Files to Staging

    Add files to the staging area to prepare them for committing.

    git add <file1> <file2> ...

    Use git add . to add all files in the current directory.

  5. Step 5: Commit Your Changes

    Commit your changes to the repository with a descriptive commit message.

    git commit -m "Your descriptive commit message here"
  6. Step 6: Check Repository Status

    Check the status of your repository to see which files are modified, staged, or untracked.

    git status
  7. Step 7: View Commit History

    View the commit history to see a list of commits along with their messages and other details.

    git log
  8. Step 8: Create and Switch Branches

    Create a new branch for working on a new feature or experiment.

    git branch <branchname>

    Switch to the new branch:

    git checkout <branchname>

    Alternatively, create and switch to a new branch in one step:

    git checkout -b <branchname>
  9. Step 9: Merge Branches

    Once you're done with changes in a branch, merge it back into the main branch (e.g., master).

    git checkout master
    git merge <branchname>
  10. Step 10: Push to Remote Repository

    If you're collaborating with others or want to back up your code remotely, push your changes to a remote repository.

    git remote add origin <remote-repository-url>
    git push -u origin master

    Replace <remote-repository-url> with the URL of your remote repository (e.g., on GitHub, GitLab, or Bitbucket).

  11. Step 11: Pull Changes from Remote

    If others have made changes to the remote repository, fetch and merge those changes into your local repository.

    git pull origin master
  12. Step 12: Clone an Existing Repository

    To clone an existing repository from a remote server to your local machine, use the following command. This creates a local copy of the remote repository.

    git clone <repository-url>