Git platform automates build, test, and deployment procedures, making it essential to Infrastructure as Code (IaC), Continuous Integration/Continuous Delivery (CI/CD) pipelines, and other DevOps approaches. Platforms that build on Git, such as GitHub, GitLab, and Bitbucket, offer robust collaboration tools including code reviews and pull requests. As learning Git is essential for developers, we have come up with a complete Git tutorial to streamline your workflow for your projects. Learn more with our Git course syllabus.
Git Basics for Beginners
Here are the fundamental concepts to learn about Git. Before that we explore repositories.
What is a repository?
A repository is a central location for managing and storing data or digital artifacts. Depending on its intended use, a repository’s features and the kind of content it stores can change.
Here are a couple of common types:
Software Repository (or code repository): The code and associated data for software projects are kept and managed by developers in a software repository. In order to track changes over time and promote collaboration, they frequently incorporate version control systems.
Examples: Bitbucket, GitLab, and GitHub.
Data Repository: A central location for managing and storing datasets for analysis, reporting, and sharing is called a data repository. It can include archives and huge databases.
Examples: Data lakes and warehouses.
Local and Remote Repositories
Local Repository: On your personal computer, there is a local repository. Usually, you start a project there or clone a remote repository there. You manage the history of your project locally, make changes, and commit them. Consider it your own workstation for the project.
Remote Repository: On the other hand, a remote repository is housed on a server and is frequently reachable via the internet or a network (as on platforms like GitHub, GitLab, or Bitbucket). It acts as a hub for cooperation, enabling several developers to exchange and coordinate their work. It serves as a backup for your project as well.
Feature | Local Repository | Remote Repository |
Location | Your computer | Server (online or on a network) |
Purpose | Personal work, local history tracking | Collaboration, sharing, backup |
Working Copy | Usually has a working copy of the files | Typically doesn’t have a working copy (“bare”) |
Interaction | Primarily where you make and commit changes | Used for pushing and pulling changes to/from others |
- Your local repository is where you work.
- To share your work and receive updates from others, you utilize the remote repository.
For example, if you and your team are working on a software project, you would:
- You should write code in a local repository on your machine.
- To make your finished modifications visible to your teammates, push them to a shared remote repository (such as GitHub).
- To obtain the most recent updates from your team, pull changes from the remote repository to your local repository.
Join our Git Online Course Program.
Git Basic Commands
Here are two basic git commands:
Initializing New Repository with Git Init
A basic Git command called git init can be used to either re-initialize an existing Git repository or establish a new, empty one.
It does the following:
- Git init generates a new.git subdirectory when it is executed in a directory that isn’t already a Git repository. All of the metadata required for the new repository, including objects, references, and template files, is contained in this hidden directory.
- Nothing will be broken if you run git init in an existing Git repository. It won’t replace any current configurations or history; it will simply re-initialize.
How to utilize it:
- Open the command prompt or terminal.
- Use the cd command to get to your project’s root directory.
- After typing git init, hit Enter.
Output:
Initialized empty Git repository in /path/to/your/project/.git/
Your project directory is now a Git repository after executing git init, and you can begin monitoring changes with git add and git commit.
Cloning an Existing Repository using Git Clone
To make a duplicate of an existing remote repository on your local computer, use the Git command git clone. The complete repository, including all of the files, branches, and history, is downloaded.
It is similar to creating a full copy of a remote project so that you may work on it locally.
How to utilize it:
Usually, you use git clone and then the remote repository’s URL.
git clone <repository_url>
To clone a repository from GitHub, you could do:
git clone https://github.com/username/repository_name.git
What occurs when a git clone is run:
- Git generates a new directory, which is either called after the repository by default or can be renamed.
- All of the data is copied into this new directory from the remote repository.
- It ensures that you have a functional copy of the project files by checking out the default branch, which is typically main or master.
- You may simply interact with the original repository by setting up the remote repository as a “remote” called origin (e.g., to pull updates or push your changes).
The Working Directory, Staging Area, and Repository:
Understanding the three “trees” of Git and how changes move between them.
Working Directory: All of your file modifications are made here. It’s what your file explorer displays.
- These are the real files on your local computer that are part of your project. Unless you instruct it to do so, Git does not automatically track these changes.
Staging Area (or Index): This serves as a barrier between the repository and your working directory.
- To decide which of your modifications in the working directory to include in your subsequent commit, you utilize the staging area.
- Consider it as creating a snapshot of your modifications.
Repository (.git directory): Git keeps track of all the commit history for your project here, along with the objects (file snapshots) and metadata. It serves as a record of every modification that has been made.
Changes usually flow between these three areas as follows:
- You make changes: Files in your Working Directory can be added, changed, or removed.
- Although Git is currently aware that these files have changed, Git has not yet committed these changes to its tracking.
- You stage changes: To transfer particular changes from your Working Directory to the Staging Area, use the git add command.
- This indicates to Git, “These are the changes I want to include in my next snapshot (commit).”
- You commit changes: The modifications that are presently in the staging area are saved as a permanent snapshot in your repository using the git commit command.
- A message outlining the changes is included with every commit.
Visual Analogy:
Consider photographing for a scrapbook:
- Working Directory: All of your loose photographs on your desk.
- Staging Area: A table on which you have chosen the pictures you wish to use for your scrapbook’s subsequent page.
- Repository: The actual scrapbook containing all of the finished pages (commits).
Common Git Commands and Their Relation to the Trees:
Here are the common git commands and their relation to the trees:
- git status: Indicates how your staging area and working directory are doing. It lets you know which files are staged, which are not tracked, and which have been altered.
- git add <file>: Transfers modifications to the Staging Area from the Working Directory.
- git rm –cached <file>: It eliminates a file from the Staging Area (but keeps it in the Working Directory).
- git reset <file> HEAD: It returns a file to the Working Directory from the Staging Area (as unstaged changes).
- git commit -m “Your commit message”: Generates a new commit in the repository using the modifications from the staging area.
- git checkout — <file>: Reverts the file to the version in the Staging Area (or the last commit if it isn’t staged), discarding modifications made in the Working Directory.
To use Git effectively, you must comprehend these three locations and how changes move between them.
Recommended: DevOps course in Chennai.
Basic Workflow in Git
The following steps are commonly included in the basic Git workflow:
Make Changes: You can alter files located in your Working Directory. This could entail updating already-existing content, introducing new features, or repairing errors.
Stage Changes: The git add command is used to choose the changes you wish to include in your subsequent commit. By doing this, the modifications are transferred from your Working Directory to the Staging Area.
git add <filename>
# or to stage all changes
git add .
Commit Changes: The git commit command is used to save the staged changes to your local repository. Writing a succinct and understandable commit message outlining the changes is best practice.
git commit -m “Describe your changes here”
Push Changes: To enable others to view your work when working with a remote repository (such as GitHub), you will use the git push command to transmit your local commits to the remote repository.
git push origin <branch_name>
Pull Changes: The git pull command is used to import changes from the remote repository into your local repository if someone else has made any modifications.
git pull origin <branch_name>
Thus, an extremely typical cycle looks like this:
Make Changes -> Stage Changes -> Commit Changes -> (Push Changes)
When working together, it frequently turns into:
(Pull Changes) -> Make Changes -> Stage Changes -> Commit Changes -> Push Changes
Related: Docker Training in Chennai.
Branching and Merging in Git
With Git, branching lets you continue working on a project without interfering with the primary stream of development. One considers it the beginning of a new, autonomous course of development.
Why use branches?
When developing new features, addressing bugs, or testing concepts separately, branches are immensely helpful. Your primary codebase remains stable as a result.
The main branch:
Usually called main or master, Git comes with a main branch by default. The stable, production-ready version of your code is typically represented by this branch.
Creating a new branch:
To make a new branch, use the git branch command and then the name you want for it. The git checkout command is used to switch to that new branch. You can use git checkout -b to combine these two processes.
git branch feature-x # Creates a new branch named “feature-x”
git checkout feature-x # Switches to the “feature-x” branch
# Or, combined:
git checkout -b feature-y # Creates and switches to “feature-y”
Viewing branches:
To view a list of all your branches, both local and remote,
git branch -a
An asterisk (*) is typically used to indicate the branch that is currently active.
Merging in Git
The process of incorporating modifications from one branch—such as a feature branch—into another—such as the main branch—is known as merging. By doing this, the work completed on the distinct branch is incorporated back into the main development stream.
How merging works:
Git tries to merge the modifications made to both branches when you merge them.
The git merge command:
Put the name of the branch you wish to merge into your currently active branch, then the git merge command.
# Assuming you are on the ‘main’ branch
git checkout main
git merge feature-x # Merges the changes from ‘feature-x’ into ‘main’
Merge conflicts:
Git may not always be able to automatically fix modifications made to the same lines in the same file that have been altered differently on the branches being merged.
- You will have to manually settle the merge conflict by selecting which changes to retain.
- Git will highlight the places in the impacted files that are in dispute.
While, working on separate lines of development is made possible via branching, you can incorporate modifications from one branch into another by merging them. This is an essential component of Git collaborative processes.
Related: Ansible Course in Chennai.
Working with Remote Repositories
Versions of your project stored on the internet or another network are known as remote repositories. They are essential for backups and teamwork.
When using remote controls, you’ll frequently do the following tasks:
Adding a Remote:
The git remote add command is used to connect a local repository to a remote one (such as on GitHub, GitLab, or Bitbucket). Usually, you give the remote a brief name that is customary.
git remote add origin <remote_repository_url>
For example:
git remote add origin https://github.com/yourusername/your_repo.git
Viewing Remotes:
You can use the following to see which remote repositories your local Git is monitoring:
git remote -v
This will display the remotes’ names together with the URLs that correspond to them (both for pushing and fetching).
Pushing to a Remote:
The git push command is used to transfer your local commits to a remote repository. The branch you wish to push and the remote name must be specified. You may need to set up a tracking connection with the -u parameter the first time you push a local branch to a remote.
git push origin <your_branch_name>
# With -u to set up tracking (only needed the first time for a branch)
git push -u origin <your_branch_name>
Pulling from a Remote:
The git pull command is used to pull the most recent changes from a remote repository into your local repository. The changes are then automatically merged into your existing local branch after being fetched.
git pull origin <remote_branch_name>
You can frequently use git pull if you’re on a branch that is tracking a remote branch (configured with git push -u).
Fetching from a Remote:
The git fetch command does not attempt to incorporate commits and objects into your local branches; instead, it downloads them from the remote repository. After that, you can examine these modifications and choose how to combine them.
git fetch origin
You may then run git merge origin/\branch_name> to incorporate the changes after fetching.
Renaming a Remote:
Git remote rename can be used to modify a remote’s name.
git remote rename origin upstream
Removing a Remote:
Git remote remove can be used to get rid of a specific remote if you are no longer using it.
git remote remove origin
Common Workflow with Remotes:
- Clone: Use git clone to copy a remote repository to your computer.
- Make: Locally make modifications (add, commit).
- Push: Use git push to upload your local changes to the remote repository.
- Pull: To obtain updates from other people, pull modifications from the remote repository (git pull).
Related: Nagios Course in Chennai.
Undoing Changes in Git
Depending on what you want to undo and where you are in the process, Git offers multiple options to accomplish it.
The following lists typical situations along with the Git commands you might use:
Undoing Changes in the Working Directory (Before Staging):
To remove modifications made to a particular file: You can use the following to restore a file in your working directory to its most recent committed version after making changes to it:
git checkout — <filename>
By doing this, the modifications you made to that file in your working directory will be permanently erased.
Undoing Changes in the Staging Area (Before Committing):
In order to unstage a certain file: If you wish to remove a file from the staging area after adding it there (git add) but not yet committing, use:
git reset HEAD <filename>
This will make an unstaged change and return the file to your working directory.
To undo all of the changes: You can use the following to unstage everything you’ve added using git add:
git reset HEAD
Undoing Commits:
Since you’re changing history, this is where things become a little more complicated.
To undo the last commit (but keep the changes): After making a commit, if you decide you want to add more files or make changes, you can use:
git reset –soft HEAD^
The modifications from the undone commit remain in your staging area, but the HEAD pointer will be moved back to the commit that came before the last one. After that, you can stage any additional modifications and commit once more.
To undo the last commit (and unstage the changes): To fully reverse the most recent commit and restore the modifications to your working directory (unstaged), use:
git reset –mixed HEAD^
# This is the default behavior of git reset, so you can also just do:
git reset HEAD^
To undo the last commit (and discard the changes): To fully reverse the previous commit and remove the modifications it brought about, use:
git reset –hard HEAD^
This operation is harmful. The modifications from the undone commit will be lost. Be careful when using it!
To undo an older commit (and create a new commit that undoes the changes): Git revert can be used to reverse a prior commit while keeping history intact; this is advised for shared repositories. This results in a new commit that undoes the modifications made by the target commit.
git revert <commit_hash>
To write the commit message for the revert commit, Git will often launch an editor.
Which method to choose depends on your situation:
- use git checkout — <file>: If you haven’t staged yet.
- use git reset HEAD <file>: If you’ve staged but not committed.
- use git reset –soft HEAD^: If you just committed and want to amend.
- use git reset –mixed HEAD^: If you want to undo a commit and keep the changes locally.
- use git reset –hard HEAD^ (be careful!): If you want to undo a commit and discard the changes (locally!).
- use git revert <commit_hash>: If you want to undo a commit and create a new commit that reverses it (safer for shared repos).
Recommended: Docker Tutorial for Beginners.
Ignoring Files using .gitignore
You may instruct Git which files and folders it should not track with this useful Git tool. These are usually files created during the development process, such as sensitive data, temporary files, build outputs, or IDE-specific settings.
How it works:
In the root directory of your repository, you create a plain text file called.gitignore (or in any subdirectory to affect only that directory and its subdirectories). Lines in this file identify patterns that Git should ignore.
Common things to ignore:
- Build artifacts (e.g., target/, bin/)
- Package dependency directories (e.g., node_modules/, venv/)
- Operating system temporary files (e.g., .DS_Store)
- IDE-specific files and directories (e.g., .idea/, .vscode/)
- Log files
- Private configuration files (e.g., sensitive API keys)
Syntax of .gitignore:
- A pattern is specified by each line.
- Lines that are blank are disregarded.
- Lines that start with # indicate comments.
- Typical glob patterns function as follows:
- * matches to zero or more characters.
- ? matches to precisely one character.
- [] Any character enclosed in brackets is matched. (for example, [abc] matches ‘a’, ‘b’, or ‘c’).
- [!…]: Any character that is not enclosed in brackets is matched by it.
- a trailing /: Only folders are matched by a trailing / on a pattern (build/, for example, will disregard the build directory and anything inside it).
- A leading! undermines a pattern that would be disregarded otherwise. For instance, if you wish to include important.log but disregard all.log files, you would have:
*.log
!important.log
Example .gitignore file:
# Ignore build output
build/
target/
# Ignore node modules
node_modules/
# Ignore operating system files
.DS_Store
# Ignore IDE settings
.idea/
.vscode/
# Ignore log files
*.log
# Don’t ignore this specific log file
!important.log
# Ignore temporary files
*.tmp
Important points:
- Even if a file fits a pattern in.gitignore, it will not be ignored if Git is already tracking it. First, you would need to use git rm –cached to untrack it.
- Creating a.gitignore file early in the development of your project is generally a smart idea.
- For a variety of programming languages and IDEs, there are numerous community-maintained.gitignore templates accessible online (for example, on GitHub under “github/gitignore”).
To begin using.gitignore, just create a file in the root of your repository with the file and directory patterns you want Git to ignore in it.
Explore all our software training courses at SLA.
Conclusion
The fundamental concepts of Git have been covered in this complete Git tutorial for beginners, including branching, merging, working with remote repositories, initializing repositories, and making changes. Try new things and learn more with our Git training in Chennai as you proceed on your Git journey.