Lesson 03 beginner

Git Basics

The three areas of Git, the everyday loop of status, add and commit, reading history with log and show, comparing changes with diff, staging part of a file, ignoring files with .gitignore and renaming or deleting tracked files.

This is the lesson you will use every single day. You create the Orbit repository, learn the three places a change passes through on its way into history and practise the loop that makes up most of Git: change, check, stage, commit.

The three areas

Every change in Git moves through three areas:

AreaAlso calledWhat it holds
Working treeWorking directoryThe files on disk that you edit
Staging areaIndexThe changes you have picked for the next commit
Repository.git directory, historyEvery commit ever made

The staging area is what makes Git different from “save a copy”. It lets you edit five files and then commit them as two separate, focused commits: one that fixes a bug and one that updates the docs. Reviewers, git revert and git bisect all work better with small commits that do one thing.

  edit        git add        git commit
 ------>  working tree  ------>  staging area  ------>  repository

Create the Orbit repository

$ mkdir orbit && cd orbit
$ git init
Initialized empty Git repository in /home/ana/orbit/.git/
$ ls -a
.  ..  .git

git init only creates the hidden .git directory. That directory is the repository: delete it and the folder is just files again, with no history. Never edit files inside .git by hand.

The everyday loop

Create two files and ask Git what it sees:

$ printf "# Orbit\n\nA small notes app.\n" > README.md
$ printf "const port = 8080;\nconsole.log('Orbit API on ' + port);\n" > server.js
$ git status
On branch main

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	README.md
	server.js

Untracked means Git sees the files but does not manage them yet. Stage them, check again and commit:

$ git add README.md server.js
$ git status --short
A  README.md
A  server.js
$ git commit -m "Add README and API entry point"
[main (root-commit) 5d1e0a2] Add README and API entry point
 2 files changed, 4 insertions(+)

Now change a file and look at the short status again. The two columns are “staged” on the left and “not staged” on the right:

$ echo "console.log('ready');" >> server.js
$ git status -s
 M server.js
$ git add server.js
$ git status -s
M  server.js
Short statusMeaning
??Untracked file
A New file, staged
MModified, not staged
M Modified and staged
MMStaged, then modified again
DDeleted, not staged

Tip: Run git status before every add and every commit. It costs nothing and tells you exactly what the next command will do.

Writing the commit

git commit -m "message" is fine for one-line messages. Without -m, Git opens your editor so you can write a subject line and a longer explanation. Lesson 17 covers what a good message looks like.

Two shortcuts you will meet:

  • git commit -a -m "message" stages every tracked file that changed, then commits. It never adds new, untracked files.
  • git commit --amend replaces the last commit with a new one that includes what is staged now, and lets you fix the message. Only amend commits you have not pushed yet.

Comparing changes with diff

git diff answers “what exactly did I change?”. Which comparison you get depends on the arguments:

CommandCompares
git diffWorking tree with staging area (changes not staged yet)
git diff --stagedStaging area with the last commit (what will be committed)
git diff HEADWorking tree with the last commit (everything)
git diff main featureTwo branches or commits
git diff --statSame as git diff, but only file names and line counts
$ echo "const host = '0.0.0.0';" >> server.js
$ git diff
diff --git a/server.js b/server.js
--- a/server.js
+++ b/server.js
@@ -1,3 +1,4 @@
 const port = 8080;
 console.log('Orbit API on ' + port);
 console.log('ready');
+const host = '0.0.0.0';

Lines starting with + were added and lines starting with - were removed. The @@ header tells you the line numbers of the change.

Staging part of a file

Sometimes one file holds two unrelated changes. git add -p (patch mode) shows each change, called a hunk, and asks what to do with it:

$ git add -p server.js
@@ -1,3 +1,4 @@
...
Stage this hunk [y,n,q,a,d,s,e,?]? y

y stages the hunk, n skips it, s splits it into smaller hunks and q quits. J and K jump to the next or previous hunk, and since Git 2.54 patch mode also shows whether a hunk you return to was already accepted or skipped. Patch mode is the habit that turns messy working sessions into clean commits.

Reading history

$ git log --oneline
9b7c3f4 (HEAD -> main) Log readiness and bind host
5d1e0a2 Add README and API entry point
$ git log --oneline --graph --all     # every branch, drawn as a graph
$ git log -p -2                       # the last two commits with their diffs
$ git log --stat                      # files changed in each commit
$ git log --author="Ana" --since="2 weeks ago"
$ git log -- server.js                # only commits that touched this file
$ git show 9b7c3f4                    # one commit: message and diff
$ git show HEAD~1:server.js           # a file as it was one commit ago

HEAD means “the commit you are on”. HEAD~1 is its parent, HEAD~2 the grandparent and so on.

Ignoring files

Some files must never be committed: dependencies, build output, logs and above all secrets. List them in a .gitignore file at the root of the repository and commit that file:

# dependencies and build output
node_modules/
dist/

# local configuration and secrets
.env
*.pem

# editor and OS noise
.vscode/
.DS_Store
*.log
$ git check-ignore -v .env
.gitignore:6:.env	.env

.gitignore only affects untracked files. If .env was already committed, ignoring it does nothing until you stop tracking it with git rm --cached .env, and the secret is still in history: rotate it. For files you want to ignore only on your machine, use .git/info/exclude, which is never shared.

Warning: Once a secret is pushed, assume it is compromised. Removing it in a new commit does not remove it from history. Revoke the key first, then clean up.

Deleting and renaming tracked files

$ git rm old-notes.txt          # delete the file and stage the deletion
$ git rm --cached .env          # stop tracking, keep the file on disk
$ git mv server.js api.js       # rename and stage the rename

You can also rename or delete with normal tools and then git add -A; Git detects renames by comparing content, not by remembering the command you used.

Quick reference

TaskCommand
Create a repositorygit init
What changed?git status / git status -s
Stage filesgit add <file> / git add -A
Stage part of a filegit add -p
Commitgit commit -m "message"
Fix the last unpushed commitgit commit --amend
Unstaged / staged changesgit diff / git diff --staged
Historygit log --oneline --graph --all
One commitgit show <commit>
Stop tracking a filegit rm --cached <file>

Exercise

You edited server.js and README.md. You want to commit only the server.js change now. Which sequence does it?

  1. git commit -a -m “Fix port”
  2. git add -A, then git commit -m “Fix port”
  3. git add server.js, then git commit -m “Fix port”
  4. git commit -m “Fix port” server.js README.md
Show answer

Answer: C. Only staged changes go into a commit. Staging just server.js leaves the README change in the working tree for a later commit. -a and -A would include both files.

Exercise

git diff prints nothing, but git status shows server.js as modified. What is going on?

  1. The file changed only in whitespace
  2. The change is already staged, so you need git diff –staged to see it
  3. Git is broken and the index must be rebuilt
  4. The file is listed in .gitignore
Show answer

Answer: B. Plain git diff compares the working tree with the staging area. Once a change is staged, those two match, so the diff is empty. git diff –staged shows what will be committed.

Exercise

A teammate committed .env with a database password last week. Today you add .env to .gitignore. What else is needed?

  1. Run git rm –cached .env, commit, and rotate the password because it stays in history
  2. Nothing, .gitignore removes it from history
  3. Run git status so Git rereads the ignore file
  4. Delete the .gitignore file and create it again
Show answer

Answer: A. .gitignore only stops untracked files from being added. A tracked file stays tracked until git rm –cached, and every old commit still contains the password, so the secret must be changed.

Key takeaways

  • Changes move from the working tree to the staging area (git add) to the repository (git commit).
  • git status and git diff before committing keep surprises out of your history.
  • git diff shows unstaged changes, git diff --staged shows what the next commit contains.
  • git add -p stages part of a file so each commit does one thing.
  • .gitignore keeps dependencies, build output and secrets out, but cannot remove what is already committed.

FAQ

Why does Git need a staging area? Other tools commit everything.

It lets you shape commits. You can work freely, then commit related changes together and leave the rest for later. Small, focused commits are easier to review, revert and search with git bisect.

What is the difference between git add . and git add -A?

In modern Git both stage new, modified and deleted files. git add . limits itself to the current directory and below, while git add -A covers the whole repository wherever you run it.

Can I commit an empty folder?

No. Git tracks files, not directories. The usual trick is to put a placeholder file such as .gitkeep inside the folder.

How do I see what a file looked like in an older commit?

Use git show <commit>:<path>, for example git show HEAD~3:server.js. To get that version back into your working tree, use git restore --source=HEAD~3 server.js (lesson 9).

Should I use git commit -a?

It is fine when every change in tracked files belongs in the same commit. Remember that it skips untracked files, so a new file you forgot to add will be missing from the commit.

Where do I put a .gitignore that applies to all my repositories?

Create a file such as ~/.config/git/ignore, which Git reads by default, and list personal noise there (editor folders, .DS_Store). Keep project rules, such as node_modules/, in the project’s own .gitignore so the whole team shares them.

↑ ↓ navigate Enter open Esc close