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
-
Step 1: Install Git
Install Git using your Linux distribution's package manager.
For Debian/Ubuntu-based systems:
sudo apt update sudo apt install gitFor Fedora/RHEL-based systems:
sudo yum install git -
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" -
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 -
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. -
Step 5: Commit Your Changes
Commit your changes to the repository with a descriptive commit message.
git commit -m "Your descriptive commit message here" -
Step 6: Check Repository Status
Check the status of your repository to see which files are modified, staged, or untracked.
git status -
Step 7: View Commit History
View the commit history to see a list of commits along with their messages and other details.
git log -
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> -
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> -
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 masterReplace
<remote-repository-url>with the URL of your remote repository (e.g., on GitHub, GitLab, or Bitbucket). -
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 -
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>