Git for Developers: A Complete Guide with Examples
Git is the most widely used version control system in modern software development. It allows developers to track changes, collaborate efficiently, and manage codebases. This guide will walk you through Git installation, configuration, and essential commands with detailed examples.
1. Installing Git
Install Git on your system depending on your operating system:
Windows
Download the installer from git-scm.com and follow the setup wizard.
macOS
brew install git
Linux
sudo apt update
sudo apt install git
2. Git Configuration
After installation, configure Git with your name and email:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
To check configuration:
git config --list
3. Creating a Repository
mkdir my-project
cd my-project
git init
This initializes a new Git repository in the my-project
directory.
4. Basic Git Workflow
The typical workflow includes the following steps:
- Create or modify files
- Check status
- Stage changes
- Commit changes
git status
git add filename
# or all changes
git add .
git commit -m "Your commit message"
5. Working with Remote Repositories
To connect your local repo with a remote GitHub repository:
git remote add origin https://github.com/yourname/repo.git
git push -u origin main
To pull updates:
git pull origin main
6. Branching and Merging
Create and switch to a new branch:
git checkout -b new-feature
Merge it into main:
git checkout main
git merge new-feature
7. Viewing History
git log
# One line summary
git log --oneline
8. Cloning a Repository
To copy a remote repository locally:
git clone https://github.com/username/repo.git
9. Ignoring Files
Use a .gitignore
file to exclude files from Git tracking:
node_modules/
.env
.DS_Store
10. Reset and Revert
Undo local changes:
git restore filename
Reset commit history (destructive):
git reset --hard HEAD~1
To safely undo a commit:
git revert HEAD
11. Git Best Practices
- Write clear commit messages
- Use branches for features/fixes
- Pull often to stay updated
- Do not commit secrets
- Use .gitignore wisely
12. Conclusion
Git is essential for modern development. Whether you're working alone or with a team, mastering Git helps you manage projects efficiently and safely. Start using Git daily and gradually explore its advanced features like rebasing, stash, and hooks.