Git Basics
Repositories, commits, staging and reading history.
What you will learn
- Init a repo and commit
- Understand the staging area
- Read git log and diff
Git is a version control system: it records the history of your project so you can see what changed, when and why, go back to any earlier state, and work with others without overwriting each other. Almost every software team uses it.
git --version
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch mainThe three areas
- Working directory: your files as they are right now.
- Staging area (index): the changes you have chosen to include in the next commit.
- Repository: the permanent history of commits.
The staging area is what lets you craft a clean commit from a messy day of edits: stage only the related changes together.
mkdir my-project && cd my-project
git init
echo "# My Project" > README.md
git status # what is going on?
git add README.md # stage it
git commit -m "Add README" # record it[main (root-commit) a1b2c3d] Add README 1 file changed, 1 insertion(+) create mode 100644 README.md
# edit files...
git status # see changed files
git diff # see what changed (unstaged)
git add -p # stage chosen hunks interactively
git add . # or stage everything
git diff --staged # review what will be committed
git commit -m "Fix login redirect"git log # full history
git log --oneline --graph -10 # compact view
git show a1b2c3d # one commit's changes
git blame README.md # who last changed each lineGood commits
- One logical change per commit. It should be easy to describe in one line.
- Write in the imperative: "Add search filter", not "added" or "stuff".
- Keep the first line under about 50 characters; add detail after a blank line if needed.
.gitignore
List files Git should never track: dependencies, build output, secrets.
node_modules/
.venv/
__pycache__/
.env
.DS_Store
dist/API keys and passwords committed once stay in history even after you delete them. Keep them in .env (ignored) and rotate any key that leaks.
Try it yourself
Create a repo, make three commits (add a file, edit it, add another), then use git log --oneline and git show to view the second commit.
Show solution
git init demo && cd demo
echo "one" > a.txt && git add a.txt && git commit -m "Add a.txt"
echo "two" >> a.txt && git commit -am "Edit a.txt"
echo "b" > b.txt && git add b.txt && git commit -m "Add b.txt"
git log --oneline
git show HEAD~1