A beginner's guide to version control and collaboration.
Git is a distributed version control system. Think of it as a "save button" on steroids for your code history.
It tracks changes in your files, so you have a record of what has been done, and you can revert to specific versions should you ever need to.
While Git is the tool you use locally, GitHub is a website where you upload your Git repositories.
First, tell Git who you are (run this once per computer):
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"To start using Git in your current project folder:
git initSaving in Git is a two-step process: Add (stage) and Commit (save).
# Check which files have changed
git status
# Add specific file
git add filename.txt
# OR Add all changed files
git add .
# Save the changes with a message
git commit -m "Added a new feature"Branches allow you to work on different features simultaneously.
# Create a new branch named 'feature-login'
git branch feature-login
# Switch to that branch
git checkout feature-login
# SHORTCUT: Create and switch in one command
git checkout -b feature-loginOnce you finish your work on the branch, you can merge it back to main (usually done via Pull Request on GitHub, or locally).
Link your local folder to a repository you created on GitHub.
# Link remote repository (do this once)
git remote add origin https://github.com/username/repo-name.git
# Rename main branch to 'main' (if not already)
git branch -M main
# Push your code to GitHub
git push -u origin mainAlways pull the latest changes before you start working if you are collaborating with others: git pull origin main
! [rejected] main -> main (fetch first)
error: failed to push some refs to '...'
This happens when someone else pushed code while you were working. You need to pull their changes before you can push yours.
Creates a "Merge commit" joining the histories. Simple but messy history.
git pull origin mainMoves your commits on top of the remote changes. Linear history.
git pull --rebase origin mainIf you and your teammate edited the same lines in the same file, Git won't know whose to keep. It will pause and ask you to fix it.
<<<<<<< HEAD markers.git add . to mark as resolved.git rebase --continue (if rebasing) or commit (if merging).Useful if you accidentally committed `.env` or `node_modules` and then added it to `.gitignore`.
git rm --cached filenameFor folders: git rm -r --cached foldername
To stop tracking the project entirely (un-init). This deletes the history but keeps your files.
# Windows (PowerShell)
rm -r -force .git
# Mac/Linux
rm -rf .gitFix: Your SSH keys aren't set up. Use HTTPS url instead or generate SSH keys and add them to GitHub.
Fix: You haven't made a commit yet! Run git commit -m "init" first. usage of empty repo cannot be pushed.
Fix: Remote has changes you don't have. Run git pull origin main (or --rebase).