Git Fundamentals
Git is a distributed version control system: every clone holds the full history of the project, and you share work by exchanging commits with a remote repository.
The model
Your files live in four places, and most commands move changes from one to the next:
- Working tree: the files you edit.
- Staging area (index): the changes you have chosen for the next commit.
- Local repository: the commits you have recorded.
- Remote: a shared copy of the repository, usually named
origin.
Everyday commands
git clone <url> # copy a remote repository, including its full history
git status # what has changed, and what is staged
git add <file> # stage changes (git add -p lets you pick parts of a file)
git commit -m "..." # record the staged changes as a commit
git fetch # download remote changes without applying them
git pull # fetch, then merge into your current branch
git push # upload your commits to the remote
git log --oneline # history, one line per commit
git diff # unstaged changes (git diff --staged shows staged ones)
Fetch versus pull
git fetch only updates your view of the remote (branches such as origin/main). Your own branches and files do not change, so it is always safe. git pull is a fetch followed by a merge (or a rebase, depending on your configuration), which changes your current branch.
Habits that keep you out of trouble
- Run
git statusbefore and after every operation until it becomes automatic. - Pull before you start working and before you push, so you build on the latest state.
- Commit locally as often as you like; push when the work is ready to share.
- Read error messages. Git usually tells you what to do next.
Try it
Create a folder, run git init, add a file, and make two commits. Look at the result with git log --oneline. Then clone the repository to a second folder, make a commit there, and git pull it back into the first.
Common mistakes
- Using git add . without checking what it stages.
- Pulling with uncommitted changes and being surprised by the result.
- Pushing without pulling first, then being rejected.
Check yourself
- What is the difference between git fetch and git pull?
- A file is edited but not staged. Which of the four places holds the change?