Git Commands List with Examples

GitHub headpic
Spread the love

All Git Commands List with Examples

What is version control ?

5yBS6 3F 400x400

Version control is a system that helps manage and track changes to files over time. It allows multiple people to collaborate on a project by keeping track of modifications, who made them, and when. This is especially useful for software development, but it’s also applicable to any type of project where changes need to be monitored, such as document editing or design work.

The primary features of version control include:

  1. History Tracking: It records the history of changes, so you can see what changes were made, who made them, and when.
  2. Branching and Merging: It allows multiple versions or “branches” of a project to be developed simultaneously and then merged back together.
  3. Collaboration: It enables multiple people to work on the same project without overwriting each other’s work.
  4. Backup and Recovery: It serves as a backup system, allowing you to revert to previous versions if needed.

In the modern software development landscape, Git has become an essential tool for version control. Its flexibility, speed, and efficiency make it the choice of many developers worldwide. In this comprehensive guide, we will delve into all the essential Git commands, providing detailed examples to enhance your understanding and proficiency.

Introduction to Git

Git is a distributed version control system that allows multiple developers to work on a project simultaneously without overwriting each other’s changes. Understanding the core Git commands is crucial for effective collaboration and project management. Let’s explore the commands that will empower you to master Git.

Why use Git for your organization?

Using Git for your organization offers several benefits, making it a popular choice for version control. Here are some key reasons why Git might be the best option:

  1. Distributed Version Control: Git is a distributed version control system, meaning every developer has a complete copy of the project history on their local machine. This setup enhances collaboration, allows for offline work, and provides a backup of the codebase.
  2. Branching and Merging: Git’s lightweight branching model encourages experimentation. Developers can create branches for new features, bug fixes, or experiments without affecting the main codebase. Git also offers powerful merging capabilities, making it easier to integrate changes from different branches.
  3. Performance: Git is designed to handle large projects with efficiency. Its performance for both large and small projects is strong, with fast branching, merging, and history browsing.
  4. Collaboration: Git supports a distributed workflow, making it easier for teams to collaborate, regardless of their geographical location. Platforms like GitHub, GitLab, and Bitbucket further enhance collaboration by providing tools for code review, issue tracking, and continuous integration.
  5. Security and Integrity: Git uses cryptographic methods to ensure the integrity of the project history. Each commit is uniquely identified by a SHA-1 hash, which safeguards against data corruption and allows for easy verification of changes.
  6. Open Source and Community Support: Git is open-source and has a vast community of users and developers. This means extensive documentation, tutorials, and a wealth of third-party tools and integrations.
  7. Scalability: Git scales well with the size of the project and the number of collaborators. It can efficiently handle projects ranging from small teams to large organizations.
  8. Integration with DevOps and CI/CD: Git integrates seamlessly with various DevOps tools and Continuous Integration/Continuous Deployment (CI/CD) pipelines, streamlining the software development and release process.
  9. Flexibility: Git’s flexibility allows teams to adopt different workflows that suit their needs, whether it’s a centralized workflow, a feature branch workflow, or a Gitflow workflow.

How to install Git?

Installing Git depends on your operating system. Here are the general steps for the most common platforms: Windows, macOS, and Linux.

Windows

  1. Download Git:
  2. Run the Installer:
    • Run the downloaded .exe file.
    • Follow the on-screen instructions. You can generally go with the default settings, but you can customize the installation as needed.
  3. Finish the Installation:
    • Once the installation is complete, open “Git Bash” (you can find it in your Start menu). This provides a command-line interface for using Git.

macOS

  1. Using Homebrew:
    • If you have Homebrew installed, open your Terminal and run:
      brew install git
    • Homebrew will download and install Git for you.
  2. Manual Installation:
    • You can also download the Git installer from the official Git website and follow the instructions to install it.
  3. Xcode Command Line Tools:
    • Alternatively, Git comes with Xcode Command Line Tools. You can install them by running the following command in Terminal:
      xcode-select --install

Linux

  1. Debian/Ubuntu-based Systems:
    • Open a terminal and run:
      sudo apt update
      sudo apt install git
  2. Fedora:
    • Open a terminal and run:
      sudo dnf install git
  3. Arch Linux:
    • Open a terminal and run:
      sudo pacman -S git

Verify the Installation

After installation, you can verify that Git is installed correctly by opening a terminal or command prompt and typing:

git --version

This command will display the installed Git version if the installation was successful.

Configure Git

Once Git is installed, it’s a good idea to set your username and email address, which will be associated with your commits. You can do this by running:

git config --global user.name "Your Name"

git config --global user.email "your.email@example.com"

What is a Git SSH Key?

A Git SSH key is a cryptographic key pair used for secure communication between your computer and a remote Git server, such as GitHub, GitLab, or Bitbucket. SSH keys are a more secure and convenient alternative to using passwords for authentication.

How SSH Keys Work

  1. Key Pair: An SSH key pair consists of a private key and a public key.
    • Private Key: This key remains on your local machine and should be kept secure. It acts as your identity and should never be shared.
    • Public Key: This key can be shared freely and is uploaded to the remote Git server. It is used to verify the private key’s authenticity.
  2. Authentication Process:
    • When you try to connect to the remote server (e.g., to clone a repository or push changes), your local Git client uses the private key to sign a message.
    • The remote server checks this signature using the corresponding public key.
    • If the keys match, the server allows the connection, granting access to the repository.

Benefits of Using SSH Keys

  1. Security: SSH keys are much more secure than passwords. A private key cannot be easily guessed or stolen through traditional password-cracking methods.
  2. Convenience: Once set up, SSH keys allow password-less authentication. You won’t need to enter your username and password every time you interact with the remote server.
  3. Automation: SSH keys are useful for automation tasks, like deploying code, as they enable secure, unattended access.

Setting Up SSH Keys

  1. Generate an SSH Key Pair:
    • Use the command ssh-keygen in your terminal or Git Bash to generate a key pair. By default, this creates a key in the ~/.ssh directory.
    • Example command:
      ssh-keygen -t rsa -b 4096 -C "your.email@example.com"
    • This command creates an RSA key pair with a 4096-bit length and associates it with your email.
  2. Add the Public Key to the Git Server:
    • Copy the contents of the public key file (usually ~/.ssh/id_rsa.pub) and add it to your account on the Git server (e.g., GitHub, GitLab).
    • Each platform has a specific location for SSH key settings in your profile.
  3. Configure SSH Agent (Optional):
    • You can use an SSH agent to manage your keys and automatically enter the passphrase if your private key is protected by one. You can start the agent with ssh-agent and add your key using ssh-add.

Usage

Once your SSH key is set up and added to the remote server, you can use SSH URLs to clone repositories and push changes securely. For example, an SSH URL might look like git@github.com:username/repository.git.

Using SSH keys for Git provides a secure and efficient way to authenticate and interact with remote repositories.

VIDEO CREDIT :- BE WITH PROGRAMMER

1. Git Configuration Commands

git config

The git config command sets Git configuration values. This command controls aspects of Git’s behavior. Here are some common uses:

  • Set user name:
    git config --global user.name "Your Name"
  • Set user email:
    git config --global user.email "your.email@example.com"
  • Set default editor:
    git config --global core.editor "vim"
  • List all settings:
    git config --list

2. Git Basics

git init

The git init command initializes a new Git repository. It creates a .git subdirectory in the project root.

git init

git clone

The git clone command clones an existing repository. This command copies the repository from a remote server to your local machine.

git clone https://github.com/user/repo.git

git add

The git add command adds changes in the working directory to the staging area. It prepares the content for the next commit.

git add filename

To add all changes:

git add .

git commit

The git commit command records changes to the repository. Each commit has a unique ID and message describing the changes.

git commit -m "Your commit message"

git status

The git status command displays the state of the working directory and the staging area. It shows what changes have been staged, which haven’t, and which files aren’t being tracked by Git.

git status

git log

The git log command shows the commit history for the repository. It provides detailed information about each commit, including the author, date, and message.

git log

3. Branching and Merging

git branch

The git branch command manages branches in the repository. It lists, creates, renames, and deletes branches.

  • List all branches:
    git branch
  • Create a new branch:
    git branch new-branch
  • Delete a branch:
    git branch -d old-branch

git checkout

The git checkout command switches branches or restores working tree files. It is used to navigate between branches.

git checkout branch-name

To create and switch to a new branch:

git checkout -b new-branch

git merge

The git merge command merges changes from one branch into the current branch. It combines multiple sequences of commits into one unified history.

git merge feature-branch

git rebase

The git rebase command re-applies commits on top of another base tip. It’s an alternative to merging and can be used to keep a linear project history.

git rebase master

4. Remote Repositories

git remote

The git remote command manages the set of tracked repositories. It allows you to view and manipulate remote connections.

  • List all remotes:
    git remote -v
  • Add a new remote:
    git remote add origin https://github.com/user/repo.git
  • Remove a remote:
    git remote remove origin

git fetch

The git fetch command downloads objects and refs from another repository. It retrieves updates without merging them.

git fetch origin

git pull

The git pull command fetches and integrates changes from a remote repository into the current branch. It’s a combination of git fetch and git merge.

git pull origin master

git push

The git push command uploads local repository content to a remote repository. It sends committed changes to a remote server.

git push origin master

5. Undoing Changes

git reset

The git reset command undoes changes to the working directory and the index. It can move the HEAD to a previous commit.

  • Soft reset:
    git reset --soft HEAD~1
  • Mixed reset (default):
    git reset HEAD~1
  • Hard reset:
    git reset --hard HEAD~1

git revert

The git revert command undoes a commit by creating a new commit. It’s a safe way to undo changes.

git revert commit-id

git clean

The git clean command removes untracked files from the working directory. It’s a useful way to clean up the working space.

git clean -f

6. Stashing Changes

git stash

The git stash command temporarily shelves changes you’ve made to your working copy. It allows you to work on something else without committing changes.

  • Stash changes:
    git stash
  • Apply stashed changes:
    git stash apply
  • List stashes:
    git stash list

7. Inspecting and Comparing

git diff

The git diff command shows the differences between two data sets. It can compare the working directory, staging area, and commits.

git diff

To compare specific commits:

git diff commit-id1 commit-id2

Conclusion

Mastering Git commands is fundamental for efficient and effective project management. By understanding and utilizing these commands, you can seamlessly collaborate with your team, manage complex projects, and maintain a clean project history. Whether you’re a beginner or an experienced developer, this comprehensive list of Git commands with examples will serve as a valuable reference.

techbloggerworld.com

šŸ’» Tech l Career l startup l Developer| Job šŸ“Bangalore, KA šŸ“© work: n4narendrakr@gmail.com šŸŽ“ Ex-SDE intern at Airtel

Leave a Reply

Your email address will not be published. Required fields are marked *