GICT knowledge base
How to Use Git for Version Control
Published
Git is a distributed version control system that enables you to manage, track, and collaborate on code efficiently. As an essential tool for developers, Git helps you monitor changes, coordinate work with team members, and safeguard your project’s history. Understanding how to use Git will significantly enhance your workflow and provide robust tools for software development, documentation, and project management.
This article covers the fundamentals of Git, including installation, repository setup, committing changes, branching, merging, collaboration, conflict resolution, and advanced features. By following this comprehensive guide, you will establish a reliable version control workflow for your projects.
Prerequisites
- Basic familiarity with the command line
- A computer running Linux, macOS, or Windows
- Internet connection for downloading Git and accessing remote repositories
- Access to a code editor (such as Visual Studio Code, Atom, or Sublime Text)
Introduction to Git
Git is a version control system (VCS) designed to handle projects of all sizes with speed and efficiency. Linus Torvalds originally developed Git to manage the Linux kernel source code. Today, Git is widely used for software development, collaborative projects, content management, and more.
Git provides distributed architecture, allowing every user to have a complete local copy of the repository. This design offers resilience, flexibility, and powerful tools for branching, merging, and history management.
Install Git
Download and Install on Linux
Open your terminal.
Update your package index:
$ sudo apt update
Install Git using your package manager:
$ sudo apt install git
Verify installation:
$ git --version
Download and Install on macOS
Open the Terminal.
Install Git using Homebrew:
$ brew install git
Confirm installation:
$ git --version
Download and Install on Windows
Visit the official Git website.
Download the Windows installer and run it.
Follow the installation prompts, accepting the default options unless you have specific requirements.
Open Command Prompt or Git Bash to verify installation:
$ git --version
Configure Git
Set your identity and preferences before starting work with Git.
Set your name:
$ git config --global user.name "Your Name"
Set your email address:
$ git config --global user.email "[email protected]"
Configure your preferred text editor (optional):
$ git config --global core.editor "code --wait"
Replace code --wait with your editor command if different.
Check your configuration:
$ git config --list
[!NOTE] The --global flag applies these settings for all repositories on your system. You can override them for specific repositories if needed.
Create a New Git Repository
A Git repository (repo) is a directory that tracks changes and manages project history.
Navigate to your project folder or create a new directory:
$ mkdir myproject $ cd myproject
Initialize a new repository:
$ git init
Git creates a .git directory that contains all version control information.
Add Files and Make Your First Commit
Add files to your project folder.
Check the status of your repository:
$ git status
This command displays untracked and modified files.
Add files to the staging area:
$ git add filename
Use git add . to stage all changes in the directory.
Commit your changes:
$ git commit -m "Initial commit"
The commit message summarizes the changes for your future reference.
Track Changes and View History
Git records each change as a commit, enabling you to review project evolution and revert to previous states.
View commit history:
$ git log
Use the arrow keys to scroll, and q to exit the log view.
Show changes not yet staged:
$ git diff
Show changes between staged files and last commit:
$ git diff --staged
Branching and Merging
Create and Switch Branches
Branches enable you to develop new features, fix bugs, or experiment independently without affecting the main codebase.
Create a new branch:
$ git branch feature-branch
Switch to the new branch:
$ git checkout feature-branch
Alternatively, create and switch in one step:
$ git checkout -b feature-branch
Merge Branches
Return to the main branch (often called main or master):
$ git checkout main
Merge your changes:
$ git merge feature-branch
Git integrates changes from the feature branch into the main branch.
Delete a branch after merging:
$ git branch -d feature-branch
[!NOTE] Use branches for each feature or bug fix to maintain a clean and organized project history.
Collaborate with Remote Repositories
Remote repositories, such as those hosted on GitHub, GitLab, or Bitbucket, allow you to collaborate, back up your code, and share your work.
Add a Remote Repository
Add a remote:
$ git remote add origin https://github.com/username/repository.git
Replace the URL with your repository address.
Verify remote setup:
$ git remote -v
Push Changes to Remote Repository
Push your local commits to the remote repository:
$ git push -u origin main
The -u flag sets origin main as the default upstream for future pushes.
Pull Changes from Remote Repository
Fetch and merge changes from the remote repository:
$ git pull
This command synchronizes your local repository with the remote version.
Resolve Merge Conflicts
Merge conflicts occur when changes in different branches overlap or contradict each other.
Attempt to merge branches. If a conflict arises, Git notifies you and marks the conflicting files.
Open the conflicting files in your editor. Git marks the conflict sections like this:
<<<<<< HEAD Your changes ======= Incoming changes >>>>>> feature-branch
Edit the file to keep, modify, or combine the changes as needed. Remove the conflict markers.
Stage the resolved file:
$ git add filename
Complete the merge:
$ git commit
[!WARNING] Always review and test your project after resolving merge conflicts to ensure stability.
Ignore Unnecessary Files
Use a .gitignore file to prevent unnecessary files from being tracked by Git.
Create a .gitignore file in your repository root.
Add patterns for files and directories to exclude. For example:
*.log node_modules/ .env
Save the file. Git now ignores these files in future commits.
Use Tags for Releases
Tags mark specific points in your project’s history, such as releases or stable versions.
Create a lightweight tag:
$ git tag v1.0
Create an annotated tag with a message:
$ git tag -a v1.0 -m "Version 1.0 release"
Push tags to the remote repository:
$ git push origin --tags
Undo Changes and Restore Previous States
Git enables you to undo changes and recover previous versions.
Undo changes in a file:
$ git checkout -- filename
Unstage files:
$ git reset HEAD filename
Revert a commit:
$ git revert commit_hash
Reset to a previous commit (destructive):
$ git reset --hard commit_hash
[!WARNING] Use reset --hard with caution. This command permanently removes changes after the target commit.
Work with Forks and Pull Requests
If you contribute to open-source projects or collaborate with teams, you may work with forks and pull requests.
Fork a repository on GitHub to create your copy.
Clone your fork:
$ git clone https://github.com/yourusername/repository.git
Create a branch for your changes.
Push your branch to your fork.
Open a pull request through the hosting platform’s interface.
Stash Changes
Use the stash feature to save changes temporarily without committing them.
Stash your changes:
$ git stash
View stashes:
$ git stash list
Apply the latest stash:
$ git stash apply
Drop a stash after applying:
$ git stash drop
Working with Submodules
Submodules allow you to include external repositories inside your project.
Add a submodule:
$ git submodule add https://github.com/example/library.git
Initialize submodules:
$ git submodule update --init --recursive
Pull updates for submodules:
$ git submodule update --remote
Best Practices for Using Git
- Commit often with clear, descriptive messages.
- Use branches for each feature, fix, or experiment.
- Pull changes before pushing to avoid conflicts.
- Use
.gitignoreto keep repositories clean. - Review commit history before merging.
- Tag releases for easy reference.
- Secure your repository by keeping secrets out of version control.
Troubleshooting Common Issues
Authentication Errors
Ensure your credentials or SSH keys are configured properly. Update remote URLs to use HTTPS or SSH as needed.
Detached HEAD State
If you check out a commit directly, Git enters a detached HEAD state. Create a new branch to continue work:
$ git checkout -b new-branch
Large Files or Repository Size
Git is not optimized for very large files. Use Git Large File Storage (LFS) for binary assets.
Conclusion
By mastering Git, you gain control of your project’s history, enhance collaboration, and protect your codebase. You now have the skills to initialize repositories, track changes, collaborate with others, manage branches, resolve conflicts, and implement best practices for efficient version control. Leveraging Git enables you to handle projects of any size with confidence and security.
[!NOTE] Explore the Git documentation for advanced topics and further learning.
Related guides
Build Your Own GitHub in 10 Minutes: A Gitea VPS Setup That Actually Works
Stop paying for private repos. One Ubuntu VPS, Gitea, and ten minutes gives you your own private GitHub with free TLS certificates and no monthly fees.
GitHow to install and use Git Desktop in Windows
Github provides a Desktop app for Windows. Follow this tutorial to learn How to download, install and use Github Desktop in Windows.
