How to Use Git for Version Control: A Beginner’s Guide
Version control is a lifeline for developers, and Git is the most popular system for tracking changes in your code. It lets you save snapshots, collaborate without conflicts, and roll back mistakes. This tutorial walks you through the essential Git commands to get started quickly.
First, you need to install Git from git-scm.com and configure your name and email using git config --global user.name "Your Name" and git config --global user.email "you@example.com". Then, navigate to your project folder and run git init to create a new repository.
Tracking Changes with Basic Commands
After initializing, you can start saving versions. The workflow is simple: modify files, stage them, and commit.
- Check status –
git statusshows which files are changed or untracked. - Stage changes –
git add filenameorgit add .to stage all files. - Commit –
git commit -m "Your message"creates a permanent snapshot.
Always write clear commit messages so you (and your team) understand the history. Run git log to view past commits.
Branching for Safe Experimentation
Branches let you work on new features without breaking the main codebase.
- Create a branch –
git branch feature-name - Switch to it –
git checkout feature-name(or combine:git checkout -b feature-name) - Merge back – First checkout
main, then rungit merge feature-name
Delete unused branches with git branch -d feature-name.
Syncing with a Remote Repository
To collaborate, connect your local repo to a remote (e.g., GitHub).
- Add remote –
git remote add origin https://github.com/user/repo.git - Push commits –
git push origin main - Pull updates –
git pull origin main
Use git clone to copy an existing remote repo to your machine.
Undoing Mistakes
Git gives you safe ways to revert changes.
- Unstage a file –
git reset HEAD filename - Discard local changes –
git checkout -- filename - Undo last commit –
git reset HEAD~1(keeps changes) or--hardto delete them
Conclusion: Mastering these commands—init, add, commit, branch, merge, push, pull—will make your development workflow safer and more organized. Practice on a test repository, and soon Git will become second nature.