How to use Git for beginners
What is Git? Git plays a key role in software development. The distributed version control system has become the industry’s go-to choice due to its flexibility and robustness. This comprehensive guide covers everything you need about Git, including installation, essential commands, and advanced strategies.
Table of contents
- What is Git, and why use it?
- How to install Git on Windows
- How to install Git on Mac
- Common Git elements
- 7 basic Git commands
- How to clone a Git repository
- How to push code to a Git repository
- Difference between Git and GitHub
- Conclusion
What is Git, and why should you use it?
What is Git?
Git is a distributed version control system (DVCS) designed to manage and track changes in source code during software development. Created by Linus Torvalds in 2005, it has become the industry standard for version control. Git’s decentralized approach empowers developers to work collaboratively on projects, fostering a flexible and efficient environment for tracking changes over time.
Moreover, Git’s branching and merging capabilities significantly impact development workflows. The ability to create branches facilitates parallel development, enabling developers to work on separate features simultaneously. Once features are complete, Git’s merging functionality allows for the integration of changes back into the main codebase. This process promotes a systematic approach to feature development, reducing conflicts and ensuring code stability.
Note
While working on Git, we actively use two repositories:
Local Repository: Contains all the files and folders on our computer. It is utilized for offline changes, history reviews, and commits.
Remote Repository: It’s a server repository that can be located anywhere. Team members use it to exchange changes.
Why use Git?
Efficient Collaboration
Git facilitates seamless collaboration by providing a shared platform where team members can contribute concurrently. Whether developers are in the same office or spread globally, Git ensures efficient communication and coordination. Its decentralized nature supports concurrent work and minimizes the risk of conflicts, allowing for smoother collaboration.
Code Stability
By allowing developers to create isolated branches, Git encourages experimentation and fortifies code stability. These branches serve as dedicated spaces for feature development or bug fixes, ensuring that the main codebase remains unaffected during development. This systematic approach promotes a reliable and stable codebase for long-term project success.
Undo and Rollback
Git’s flexibility extends to its ability to roll back changes effortlessly. In addition to reverting to previous code versions, Git empowers developers to undo specific changes within a commit selectively. This fine-grained control over the version history enables quick response to unexpected issues, ensuring that the project remains on track even when faced with unforeseen challenges.
Enhanced Productivity
The efficiency of Git goes beyond its command-line interface. Git’s ecosystem includes many graphical user interfaces (GUIs) and integrations with popular development tools. This extensive toolset allows developers to choose workflows that best suit their preferences and project requirements, leading to a more tailored and productive development process.
Open Source Community
Git’s prevalence in the open-source community is not just about version control; it’s a testament to its collaborative nature. Git’s distributed architecture aligns seamlessly with the decentralized nature of open-source projects, allowing contributors worldwide to work on their forks and propose changes easily. This fosters a diverse and inclusive community, making Git an essential skill for anyone aspiring to contribute to or lead open-source initiatives.
How to install Git on Windows
Visit the official Git website and locate the download link. Click on the Download for Windows to initiate the download of the Git installer.
Once the download is complete, run the installer by double-clicking the downloaded executable file (e.g., Git-2.x.x.x-64-bit.exe). This opens the Git Setup wizard.
Follow the on-screen instructions provided by the setup wizard. Choose the default options unless you have specific preferences. Key steps include selecting the installation location, choosing the components to install (use default settings for most users), and selecting the default editor for Git (usually, choose the default, which is Vim).
During the installation, you’ll encounter an option to adjust your system’s PATH environment. Choose the default setting, Use Git from the Command line,
to ensure Git commands are accessible from the Command Prompt or PowerShell.
Choose the default line-ending conversion option unless you have a specific need for a different setting. Generally, sticking with the default Checkout Windows-style, commit Unix-style line endings
is suitable for most projects.
Complete the installation by clicking Next through the remaining steps. Once finished, click Finish to exit the installer.
Open Command Prompt or Git Bash and type the following command to verify that Git is installed:
git --version
How to install Git on Mac
If Homebrew has not been installed, open Terminal and run the following command to install Homebrew, a package manager for macOS:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
Code language: JavaScript (javascript)
Once Homebrew is installed, use the following command to install Git:
brew install git
Configure your Git username and email with the following commands, replacing Your Name and your.email@example.com with your actual name and email:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
Code language: CSS (css)
To ensure Git is installed correctly, type the following command in the terminal:
git --version
Common Git elements
Git contains several essential components, each serving a unique purpose in the version control process. Below are the fundamental elements of Git, along with their definitions:
Repository
A Git repository, or repo, is a data structure that stores metadata and a database directory for managing the project’s files, directories, and their revisions. It serves as the central hub for version control and collaboration.
Git maintains a specific set of configuration values within each repository. These values include the repository user’s name and email address. Configuration settings are not automatically carried over from one repository to another during a clone or duplication process. Git manages configurations and setups per site, user, and repository, allowing each repository to have a unique configuration.
Commit
In Git, a commit captures a snapshot of your project at a specific moment. This is identical to saving your progress in a video game, as it creates a detailed record of all the changes made. Each commit has a unique ID, author details, timestamp, and a brief message summarizing the changes. These commits are the building blocks of a visual timeline, which tells the story of your project’s growth and development.
Branch
A branch is an independent line of development in Git. It allows developers to work on features or bug fixes in isolation from the main codebase. Branches can be created, switched between, merged, and deleted, enabling parallel development.
The diagram above shows a master branch with two distinct branches: small feature and large feature. Once you have completed working on these separate branches, you can merge them to create a master branch.
HEAD
The HEAD command points to the latest commit in the current branch. It represents the version of the code currently in the working directory. Changing branches or making new commits updates the HEAD reference. Whether adding new features, fixing bugs, or exploring previous commits, HEAD ensures you’re always in sync with the most recent state of your work. Understanding HEAD is crucial for efficiently traversing your project’s timeline.
Working Directory
The working directory is the local copy of the project on a developer’s machine. It contains the files and directories that are actively being worked on. Changes made in the working directory are staged and committed to the Git repository.
Staging Area (Index)
The staging area, or the index, is an intermediate area where changes are prepared before committing. Files are added to the staging area using git add
before being committed. This allows developers to selectively include specific changes in the next commit.
Remote Repository
A remote repository is a version of the project stored on a server or another location. Developers can push changes to a remote repository to share their work with others or pull changes from a remote repository to update their local copy.
What are the 7 basic commands in Git?
Mastering Git takes time because there are many various commands you can use. However, some commands are used more frequently and are essential for a professional to know. This section will explain some commonly used Git commands that every professional should know.
Initializing a repository
Running this specific command initiates the version control in your project. This command initiates a new Git repository in the present directory, generating a hidden folder named .git
. This folder stores metadata, configurations, and the complete historical record of your project. This marks the beginning of version control, which lets you track changes, collaborate, and manage your codebase more effectively.
git init
Cloning a repository
The git clone command calls an imitation of a remote repository onto your local machine. Executing this command not only downloads the entirety of the project’s history but also establishes a functional working copy. This working copy bridges local and remote repositories, facilitating seamless collaboration, updates, and contributions. Specify <repository_url>
with the URL of the repository you intend to clone, often sourced from platforms like GitHub.
git clone <repository_url>
Code language: HTML, XML (xml)
One of the preferred ways to download the source code is by cloning with HTTPS:
git clone <https://name-of-the-repository-url>
Code language: PHP (php)
Git branching
Branches are essential in the Git world. Multiple developers can work simultaneously on a project by creating, listing, and deleting branches using the git branch
command.
Creating a new branch
git branch <branch-name>
Code language: HTML, XML (xml)
This command creates a new branch locally. By creating a new branch, you carve out a dedicated space for distinct features or fixes without perturbing the equilibrium of the main codebase. Branching is a strategic maneuver that enables a systematic and collaborative approach to project development.
To push the branch into the remote repository, use the following command:
git push -u <remote> <branch-name>
Code language: HTML, XML (xml)
Viewing branches
git branch or git branch --list
Code language: PHP (php)
Deleting a branch
git branch -d <branch-name>
Code language: HTML, XML (xml)
Checking repository status
The command git status
gives us all the necessary information about the current branch. It meticulously checks each file and categorizes them as untracked, modified, or staged for the upcoming commit. This command is a crucial preliminary step before showing in new commits, as it offers insights into what requires attention and ensures a clean slate for your next development phase.
git status
Staging changes in Git
Staging changes is akin to preparing actors for a performance. The Git add command lets you make the changes you wish to include in the upcoming commit. You can specify individual files or include all modifications using the powerful wildcard, which is a period .
. Staging is crucial, as it readies your alterations for the grand entrance into the version control spotlight.
To add a single file
git add <file>
Code language: HTML, XML (xml)
To add everything at once
git add -A
or its equivalent, shorter form:
git add .
Note:
The git add
command does not save changes to the repository. It is only when we use git commit
that the changes are saved.
Committing Git changes
This is Git’s most commonly used command. Once we reach a certain point in development, we want to save our changes. The git commit
command records your staged changes, creating a snapshot of your project at a specific moment. The -m
flag invites you to encapsulate the essence of your modifications in a brief yet informative commit message. Each commit is a landmark, contributing to your project’s evolution record.
git commit -m "Your commit message"
Code language: JavaScript (javascript)
Viewing commit history
The git log
command shows the sequence of commits, including commit hashes, authors, dates, and messages, providing a complete overview of your project’s history. It is like going on an archaeological dig into the past, offering valuable insights into the development journey. It is an essential tool for understanding the context of each change.
git log
How to clone a Git repository
This example will discuss how to clone a GitHub repository using HTTPS. To clone a Git repository, you must first copy the remote URL from your repository hosting service—for instance, GitHub.
Please open GitHub and go to the main page of the repository.
To get started, navigate to Code > Clone. Select HTTP and copy the shown repository URL.
Open the Command Prompt and use the below command to clone the repository:
git clone <repository-url>
Code language: HTML, XML (xml)
Press Enter to create the local cloned repository. The below output confirms the creation.
How to push code to a Git repository
Access your GitHub account, then click the + (plus) icon in the top right corner of the Git home page. From the dropdown menu, select New repository.
To create a new repository, you must first provide a name, description, and other necessary details.
Once you have filled in all the required information, click the Create repository button to complete the process.
Open a terminal or command prompt and navigate to the directory where your project is located. Then, run the following commands:
git init
git add
git commit -m "Initial commit"
Code language: JavaScript (javascript)
Copy the HTTPS or SSH URL of your GitHub repository. You can find this on the GitHub repository page.
Run the following command, replacing with the URL you copied:
git remote add origin <repository_url>
Code language: HTML, XML (xml)
Lastly, to push the code to GitHub, use the command below. And if you’re working on a branch other than master, replace master with the branch name.
git push -u origin main
Note
Replace main with the name of your remote branch if it happens to be different.
What is the difference between Git and GitHub?
Features | Git | GitHub |
Definition | A distributed version control system (VCS) | A web-based platform that uses Git for version control and provides additional features |
Type | Software/tool | Web-based platform |
Usage | Used for version control of code and files | Used for hosting Git repositories, collaboration, issue tracking, and project management |
Working Offline | Can work offline and does not require a connection to a server | Relies on an internet connection for most features as it’s hosted on GitHub servers |
Remote Repositories | Can work with remote repositories but does not provide a platform for hosting them | Provides a platform for hosting remote repositories, making it easy to share and collaborate |
Final thoughts on how to use Git
Developers and testers must have a good grasp of Git to enhance their productivity and work collaboratively. By learning the fundamentals, installation process, and advanced techniques, you can effectively utilize Git’s capabilities for version control in your projects. Take some time to experiment and familiarize yourself with the different commands and features of Git to become a more skilled and cooperative professional.
Related articles
Follow our blog
Be the first to know when we publish new content.
How to use Git example
- Top 10 API Testing Tools - April 6, 2024
- The ABCs of UAT Testing: Understanding User Acceptance Testing - March 21, 2024
- Agile Testing: Key Principles and Practices - March 15, 2024