Git Lesson 1: Core Fundamentals
- Explain why Git is a distributed version control system, why it stores snapshots rather than diffs, and how it compares with SVN, TFVC, and Mercurial. Distinguish porcelain commands designed for people from plumbing commands suited to scripts.
- Understand Git's object model: blobs store file contents, trees represent directories, commits record snapshots, and annotated tags carry metadata. Use
git cat-file,git hash-object,git ls-files -s, andgit write-treeto inspect whatgit commitcreates. - Work confidently across Git's three areas: the working tree, index, and repository. Read
git status, stage changes selectively withgit add -p, and distinguishgit difffromgit diff --staged. - Write clear commit messages and use
git log --oneline --graph --decorate --all,git show,git blame, andgit log -S/-Gto find who changed a line, when it changed, and why. - Undo changes safely. Understand what
restore,switch, andcheckoutdo; howreset --soft,--mixed, and--hardaffect HEAD, the index, and the working tree; when to userevertfor shared history; and when--amendis appropriate. - Remember that a branch is a movable pointer to a commit and HEAD usually names the current branch. Recognize detached HEAD and leave it safely. Work with clones, remotes, fetch, pull, push, and upstream branches; understand Git's three configuration scopes; and troubleshoot common
.gitignoreissues.
1-hour time allocation table
| # | time | module | core content | animation/interaction | Experiment (~/git-lab/myapp) |
|---|---|---|---|---|---|
| 0 | before class | Environmental preparation | Install Git 2.56, identity and default branch, editor,bootstrap-git-lab.sh | Environmental self-check list | Generate practice repository + local origin |
| 1 | 00–06 | Version control and Git architecture | Centralized vs distributed, snapshots instead of diffs, Git vs SVN/TFVC/Mercurial, porcelain vs plumbing | Centralized vs. distributed: who can work when the internet is down? | Use plumbing to see a snapshot of a commit |
| 2 | 06–14 | object model | blob/tree/commit/annotated tag, SHA-1 and SHA-256 (3.0 plan), cat-file, hash-object, .git directory, packfile | Object graph browser: click on any object to viewcat-file -p | Manually calculating blob hashes, traversing object graphs |
| 3 | 14–21 | three areas | Workspace/Index/Repository, status interpretation,add -p、diff vs --staged | core animation:git add + git commitwhen index → tree → commit → move branch ref | Partial staging area + usels-files -sObservation index |
| 4 | 21–29 | Commits, history and differences | Conventional Commits entry, log graphics, show, blame,log -S/-G | log parameter combinator (real-time display output) | Find out who FAKE_SECRET joined and when |
| 5 | 29–37 | Cancel | restore/switch vs checkout, reset three modes, revert, amend | reset mode simulator: HEAD / index / three columns of workspace | Do each of the four undos and use reflog to check the details. |
| 6 | 37–44 | Getting started with branches and HEAD | branch is 41 byte file, HEAD symbol reference, detached HEAD,switch -c | Branch pointer movement animation (commit/switch/detach) | Commit and rescue on detached HEAD |
| 7 | 44–52 | Remote repository | clone、remote、fetch vs pull、push、upstream、ahead/behind | Three-party synchronization: local ↔ origin ↔ teammates | Reproduce rejected push and solve it |
| 8 | 52–60 | Configuration, .gitignore and troubleshooting | config third level, alias, .gitignore rule,check-ignore -v、.gitattributes | .gitignore rule tester + interactive troubleshooting tree | Alias + ignore rule debugging |
| — | After class | cheat sheet · Comprehensive experiment | Complete commit/undo/push process and validate objects with underlying commands | Final exam (12 questions) | Comprehensive experiment |
Knowledge Coverage Matrix Knowledge Coverage Matrix
| target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | key commands | experiment |
|---|---|---|---|---|---|---|---|---|---|---|
| Explain distributed and snapshot models | ✓ | ✓ | · | · | · | · | ✓ | · | git clone、cat-file -p | M1 Experiment |
| Read and validate Git objects | ✓ | ✓ | ✓ | · | · | ✓ | · | · | cat-file、hash-object、ls-tree | M2 Experiment · Comprehensive Experiment |
| Control precisely what is committed next | · | · | ✓ | ✓ | ✓ | · | · | ✓ | add -p、diff --staged、restore --staged | M3 Experiment |
| Write canonical commits and retrieve history | · | · | · | ✓ | · | ✓ | · | · | log --graph、blame、log -S | M4 Experiment |
| Secure undo (local vs pushed) | · | · | ✓ | · | ✓ | ✓ | ✓ | · | reset、revert、reflog | M5 Experiment |
| The nature of branches and HEAD | · | ✓ | · | · | ✓ | ✓ | ✓ | ✓ | switch -c、symbolic-ref | M6 Experiment |
| Synchronize with remote, handle rejected | ✓ | · | · | · | ✓ | · | ✓ | ✓ | fetch、pull --ff-only、push -u | M7 Experiment |
| Configure, ignore rules and troubleshoot | · | · | · | · | · | · | · | ✓ | config --show-origin、check-ignore -v | M8 Experiment |
What’s excluded from this lesson (and where to learn it)
| Topic | Why not in this lesson | where to study |
|---|---|---|
| merge / rebase / cherry-pick, conflict resolution, stash, tag release process | This lesson only talks about what branches are; how to merge them is a collaboration topic | Lesson 2: Branching, Merging, and Teamwork |
| Certification, PR/MR, branch protection for GitHub / Azure Repos / CodeCommit / GitLab | Platform capabilities | Lessons 3 and 4 |
| Shallow cloning, Git in CI, hooks and pre-commit, signed commits | Automation theme | Lesson 5 |
| Monorepo, partial cloning, sparse checkout, LFS, branch strategy | Architecture theme | Lesson 6 |
| reflog in-depth, bisect, filter-repo clear secrets, repository damage repair | In-depth debugging topic (in this lesson, M5 only uses reflog as a "safety net") | Lesson 7 |
How to use this courseware
Principles · Diagrams · Animations · Commands · Experiments · Production Examples · Troubleshooting · Tests · Voice · Videos. It is recommended to read "Principles" and "Animation" first, and then
~/git-lab/myappLet’s do some “experiments” here.A test score ≥ 70% or clicking "Mark this module complete" will be counted as progress and saved in this browser (it will be cleared after refreshing when local storage is disabled).
The "Voice" tab uses the built-in Web Speech API (zh-CN) of the browser to read the explanation script; if there is no Chinese voice package, the explanation script can still be read or handed over to the TTS tool.
v2.56.1.windows.1(2026-11-10), Ubuntu git-core PPA is1:2.56.1-0ppa1. The commands used in this lesson are basically the same after Git 2.40;git switch/git restoreAvailable as of 2.23, the manual is no longer marked as experimental as of 2.51.Git 3.0It is planned to change the default hash of the new repository to SHA-256, the default reference storage to reftable, and the default branch name tomain, but the official BreakingChanges documentation clearly saysNo release date yet——All relevant statements about this lesson are "planned".Module 0 · Environment preparation (installation and configuration of Git)
- One host: Ubuntu 24.04 LTS (Azure VM or WSL2), macOS or Windows 11 (Git for Windows comes withGit Bash, all commands in this lesson are available in Git Bash).
- Basic shell commands will be used (
cd、ls、cat、echo). No GitHub account is required: the "remote repository" in this lesson is a bare repository on this machine. - (Optional) It’s better if you have already taken the Docker class: Practice RepositorymyappIt is the Flask + Redis counter application in the Docker class.
Step 1: Install the latest Git
| Platform | Recommended method | Description |
|---|---|---|
| Ubuntu 24.04 | ppa:git-core/ppa(“Git stable releases” maintained by Ubuntu Git Maintainers) | The noble version that comes with the system is 2.43.x, which is older; PPA was provided on 2026-11-111:2.56.1-0ppa1~ubuntu24.04.1 |
| macOS | Homebrew brew install git | The “Apple Git” version that comes with Xcode Command Line Tools lags behind the upstream; confirm after installationwhich gitPoint to Homebrew path |
| Windows | Git for Windows(winget install --id Git.Git -eOr download from gitforwindows.org) | Latestv2.56.1.windows.1(2026-11-10), comes with Git Bash and Git Credential Manager (GCM) |
| RHEL/Fedora, source code | dnf install git;Or compile from kernel.org source code | Source code compilation enables Rust components by default starting from 2.55 (requires Rust tool chain, can be turned off explicitly, see instructions below) |
# Add git-core PPA and install the latest stable version sudo apt update sudo apt install -y software-properties-common sudo add-apt-repository -y ppa:git-core/ppa sudo apt update sudo apt install -y git git --version
git version 2.56.1
brew install git hash -r # Let the shell re-search the command path which git # Apple Silicon: /opt/homebrew/bin/git Intel: /usr/local/bin/git git --version
winget install --id Git.Git -e --source winget # After reopening the terminal (or starting "Git Bash"): git --version
git version 2.56.1.windows.1
C:/Program Files/Git/etc/gitconfig), common default values arecore.autocrlf=true、pull.rebase=false, some versions will also writeinit.defaultBranch. Therefore the same command may behave differently on Windows and Linux (e.g. when forking on Linuxgit pullAn error will be reported directly asking to select a strategy, and it will be merged by default on Windows). usegit config --list --show-originSee where each value comes from (explained in detail in Module 8).make WITH_RUST=YesPlease / meson configure -Drust=enabledExplicit control.Step 2: Configure identity, default branch, and editor
# Identity: Enter the author/committer field of each commit (use your email on GitHub/Azure DevOps) git config --global user.name "Your Name" git config --global user.email "you@example.com" # The default branch name of the new repository (Git 3.0 plans to change the default value to main; now set it explicitly) git config --global init.defaultBranch main # Editor (choose one): will be opened when writing commit information and git rebase -i git config --global core.editor "code --wait" # VS Code # git config --global core.editor "vim" # git config --global core.editor "nano" # Recommended safe defaults git config --global pull.ff only # pull only allows fast forwarding, stopping when forking and letting you decide (Lesson 2 talks about rebase/merge) git config --global push.autoSetupRemote true # Automatically create upstream for the first push (Git 2.37+) git config --global fetch.prune true # Clean up remote deleted branches when fetching git config --global core.autocrlf input # Linux/macOS; use true for Windows (explained in module 8) git config --global --list --show-origin | grep -E "user\.|init\.|core\.editor|pull\.|push\.|fetch\."
file:/home/azureuser/.gitconfig user.name=Your Name file:/home/azureuser/.gitconfig user.email=you@example.com file:/home/azureuser/.gitconfig init.defaultbranch=main file:/home/azureuser/.gitconfig core.editor=code --wait file:/home/azureuser/.gitconfig pull.ff=only file:/home/azureuser/.gitconfig push.autosetupremote=true file:/home/azureuser/.gitconfig fetch.prune=true
Note --listThe output key names are all lowercase (init.defaultbranch): Git configuration section names and key names are not case-sensitive.How to verify:git var GIT_AUTHOR_IDENTDisplay the authorship to be used;git var GIT_EDITORShow editor.
Step 3: Generate practice repository (bootstrap-git-lab.sh)
Save the following script as~/bootstrap-git-lab.sh, and then executebash ~/bootstrap-git-lab.sh. It will create:
~/git-lab/myapp: Working repository, containing 12 commits and 4 local branches (main、feature/login、hotfix/redis-timeout、experiment), 2 annotation tags (v1.0.0、v1.1.0), 1 merge commit, and a "dangerous" history:settings.envever contained false secretsFAKE_SECRET=…(Used when clearing history in Lesson 7).~/git-lab/remote/myapp.git: localNaked repository, asorigin, no account or network required.~/git-lab/teammate: Simulate a clone of a teammate and have pushed 1 more commit to origin, so your myapp is ingit fetchwill be displayed laterbehind 1(For module 7).
#!/usr/bin/env bash
# bootstrap-git-lab.sh - Generate the "Git 8-Hour Crash Course" practice repository
# ~/git-lab/myapp Your working repository (main/feature/login/hotfix/redis-timeout/experiment, tag v1.0.0 v1.1.0)
# ~/git-lab/remote/myapp.git local bare repository, acting as "origin" (no account required)
# ~/git-lab/teammate simulates the clone of teammates and has pushed 1 more commit to origin.
# Usage: bash bootstrap-git-lab.sh [--force] (--force: delete and rebuild)
set -euo pipefail
LAB="${LAB:-$HOME/git-lab}"
REPO="$LAB/myapp"; REMOTE="$LAB/remote/myapp.git"; MATE="$LAB/teammate"
if [ -e "$REPO" ] && [ "${1:-}" != "--force" ]; then
echo "$REPO already exists; if you need to rebuild, please execute: bash $0 --force"; exit 1
fi
command -v git >/dev/null || { echo "git not found, please complete the installation of module 0 first"; exit 1; }
rm -rf "$REPO" "$REMOTE" "$MATE"; mkdir -p "$LAB/remote"
# Fixed author and time => The commit hash generated by everyone is exactly the same, making it easy to compare the output in the courseware
export GIT_AUTHOR_NAME="Git Lab" GIT_AUTHOR_EMAIL="lab@example.com"
export GIT_COMMITTER_NAME="Git Lab" GIT_COMMITTER_EMAIL="lab@example.com"
T=1767258000 # 2026-01-01 09:00:00 UTC
tick(){ T=$((T+3600)); export GIT_AUTHOR_DATE="@$T +0000" GIT_COMMITTER_DATE="@$T +0000"; }
g(){ git -c commit.gpgsign=false -c tag.gpgsign=false -c core.autocrlf=false "$@"; }
g init -q -b main "$REPO"; cd "$REPO"
cat > README.md <<'EOF'
#myapp
A tiny Flask + Redis hit counter used throughout the Docker and Git courses.
EOF
g add README.md; tick; g commit -q -m "chore: initial commit"
cat > app.py <<'EOF'
import os
from flask import Flask
from redis import Redis
app = Flask(__name__)
redis = Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379)
@app.route("/")
def hello():
count = redis.incr("hits")
return f"Hello from myapp! I have been seen {count} times.\n"
EOF
cat > requirements.txt <<'EOF'
flask==3.1.2
redis==6.4.0
gunicorn==23.0.0
EOF
g add app.py requirements.txt; tick; g commit -q -m "feat: add Flask app with Redis counter"
cat > Dockerfile <<'EOF'
FROM python:3.13-slim
WORKDIR/app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["gunicorn", "-b", "0.0.0.0:8000", "app:app"]
EOF
cat > compose.yaml <<'EOF'
services:
web:
build: .
ports: ["8000:8000"]
environment:
REDIS_HOST: redis
redis:
image: redis:8-alpine
EOF
g add Dockerfile compose.yaml; tick; g commit -q -m "build: add Dockerfile and compose.yaml"
cat > .gitignore <<'EOF'
__pycache__/
*.pyc
.venv/
.env
*.log
EOF
cat > .gitattributes <<'EOF'
* text=auto
*.sh text eol=lf
EOF
g add .gitignore .gitattributes; tick; g commit -q -m "chore: add .gitignore and .gitattributes"
tick; g tag -a v1.0.0 -m "release 1.0.0"
# hotfix branch: pulled from v1.0.0
g switch -q -c hotfix/redis-timeout
sed -i.bak 's/port=6379)/port=6379, socket_timeout=2)/' app.py && rm -f app.py.bak
g add app.py; tick; g commit -q -m "fix: set redis socket timeout"
g switch -q main
cat >> app.py <<'EOF'
@app.route("/healthz")
def healthz():
return {"status": "ok"}
EOF
g add app.py; tick; g commit -q -m "feat: add /healthz endpoint"
# "Dangerous" history: Fake secrets committed by mistake (only for Lesson 7 practice history cleanup, not real keys)
cat > settings.env <<'EOF'
REDIS_HOST=redis
FAKE_SECRET=fake-9f8e7d6c-not-a-real-key
EOF
g add settings.env; tick; g commit -q -m "config: add settings.env"
sed -i.bak '/FAKE_SECRET/d' settings.env && rm -f settings.env.bak
g add settings.env; tick; g commit -q -m "fix: remove FAKE_SECRET from settings.env"
tick; g merge -q --no-ff hotfix/redis-timeout -m "Merge branch 'hotfix/redis-timeout'"
tick; g tag -a v1.1.0 -m "release 1.1.0"
# Unmerged feature branches
g switch -q -c feature/login
cat > auth.py <<'EOF'
def login(user: str, password: str) -> bool:
# TODO: replace with a real identity provider
return bool(user) and bool(password)
EOF
g add auth.py; tick; g commit -q -m "feat(auth): add login stub"
echo '- POST /login (stub)' >> README.md
g add README.md; tick; g commit -q -m "docs: document /login"
# Experimental branch (Lesson 7 is used to demonstrate deletion and reflog retrieval)
g switch -q -c experiment main
echo "# experimental cache layer" > cache.py
g add cache.py; tick; g commit -q -m "wip: experiment with cache layer"
g switch -q main
# Local bare repository as origin
g init -q --bare -b main "$REMOTE"
g remote add origin "$REMOTE"
g push -q -u origin main
g push -q origin feature/login
g push -q origin --tags
g branch -q --set-upstream-to=origin/feature/login feature/login
# Teammate pushes another commit to origin => Your myapp is 1 commit behind origin/main (visible after git fetch)
g clone -q "$REMOTE" "$MATE"
(cd "$MATE"
export GIT_AUTHOR_NAME="Teammate" GIT_AUTHOR_EMAIL="mate@example.com"
export GIT_COMMITTER_NAME="Teammate" GIT_COMMITTER_EMAIL="mate@example.com"
echo '' >> README.md; echo 'Run locally: `docker compose up --build`' >> README.md
g add README.md; tick; g commit -q -m "docs: add local run instructions"
g push -q origin main )
echo "== Practice repository is ready: $REPO"
g log --oneline --graph --decorate --all
bash ~/bootstrap-git-lab.sh cd ~/git-lab/myapp
== The practice repository is ready:/home/azureuser/git-lab/myapp * fd29861 (experiment) wip: experiment with cache layer | * 912a321 (origin/feature/login, feature/login) docs: document /login | * f6f172d feat(auth): add login stub |/ * f4ac97b (HEAD -> main, tag: v1.1.0, origin/main) Merge branch 'hotfix/redis-timeout' |\ | * 17f033d (hotfix/redis-timeout) fix: set redis socket timeout * | abb417c fix: remove FAKE_SECRET from settings.env * | bbc4ca6 config: add settings.env * | 985254d feat: add /healthz endpoint |/ * ee0355b (tag: v1.0.0) chore: add .gitignore and .gitattributes * 0cbdc7a build: add Dockerfile and compose.yaml * 5e9d1b8 feat: add Flask app with Redis counter * 9c56b83 chore: initial commit
Git Lab <lab@example.com>and time (+1 hour per commit from 2026-01-01 09:00 UTC), and use-c commit.gpgsign=falseAvoid signatures that change the content, so everyone gets the exact same SHA-1. Commits you make later use your identity and the current time, and the hash will be different - this is what Module 2 is about "content addressing".warning: in the working copy of 'app.py', LF will be replaced by CRLF the next time Git touches it. This is because in the repository.gitattributesWrote* text=auto, and the default line ending in Windows is CRLF - just a reminder, the repository still stores LF, and the hash is not affected (explained in Module 8).How to reuse it in subsequent lessons
Module 0 of Lessons 2–8 all use this repository as a starting point. If the repository is "broken" by you, execute it at any timebash ~/bootstrap-git-lab.sh --forceRebuild to initial state in 1 second (will delete~/git-lab/myapp、remote/ with teammate/all changes in ). Want to put it in another directory:LAB=/tmp/lab bash ~/bootstrap-git-lab.sh。
Warm-up: Answer intuitively (30 seconds)
After cloning a 1 GB repository and disconnecting from the Internet, can I still view the complete history, create branches, and commit?
All is OK. clone willAll history(all objects) copied to local.git, log, diff, branch, and commit are all purely local operations; only fetch/pull/push requires a network. This is the "distribution" of Module 1.
Does Git save the "difference" of each modification, or the entire file?
Conceptually, there isA snapshot of the entire project on each commit(The unchanged file directly reuses the same blob); the difference isgit diffCalculated from time to time. Incremental compression is only performed when packaging (packfile). That is storage optimization, not the data model. Module 2 will be hands-on verification.
Module 1 · Version Control and Git Architecture
- In one sentence, explain the difference between centralized (SVN, TFVC) and distributed (Git, Mercurial) version control, as well as its impact on "offline work", "backup" and "permissions".
- Explain "snapshots instead of diffs": each commit points to a complete tree, and unchanged files reuse the same blob.
- Distinguish between porcelain (high-level commands for humans) and plumbing (low-level commands for scripts), and know which one to use when writing scripts.
What: What problem does the version control system solve?
A version control system (VCS) records changes to files over time and answers four questions:What has been changed(diff)、Who changed it?(author)、Why change(commit information),How to go back to the past(checkout/revert). On top of this, it also supports multiple people making parallel changes and combining the changes (branching and merging).
- Centralized VCS (CVCS): There is only one central server that holds the complete history; the client only has a "working copy" (a version of the file + a small amount of metadata). Represents: Subversion (SVN), TFVC (Team Foundation Version Control, centralized option in Azure DevOps/TFS), Perforce.
- Distributed VCS (DVCS): each clone containsfull history, itself is a fully functional repository; the "central repository" is just an ordinary copy agreed by the team. Representative: Git, Mercurial.
Why: Why Git has become the de facto standard
- Fast: Log, diff, blame, branch, and commit are all completed locally, without the need for round-trips to the server.
- Branches are cheap: A Git branch is just a small file (module 6) that records a 40-digit hexadecimal hash. It costs almost zero to create and switch, which makes the "one branch per feature + PR" workflow possible.
- integrity: All objects are named according to the hash of the content (module 2), and any tampered bit will be discovered; each clone is a complete backup.
- ecology: GitHub, Azure Repos, GitLab, Bitbucket, and AWS CodeCommit all use Git as the core; CI/CD, GitOps, and IaC tools all assume that the code is in Git.
How: Snapshot instead of diff
Early systems such as SVN conceptually saved "a string of deltas for each file." Git indata modelsaved onSnapshot: Each time you commit, Git records the status of the entire project directory tree (a tree object), and the content of each file is a blob. If a file has not changed, the new tree will directly reference it.same blob, will not be stored repeatedly.
The difference (diff) is when you executegit diff、git log -ptimeTemporarily calculated by comparing two snapshots. "Rename detection" is also inferred when comparing snapshots - Git does not log rename operations. Delta compression on disk (delta of packfile) is a later storage optimization that is transparent to the upper layer (module 2).
Git’s three-tier architecture
| layer | content | location |
|---|---|---|
| object database | blob/tree/commit/tag, addressed by hash, only added but not changed | .git/objects/(loose object + packfile) |
| References (refs) | Variable names for hashes: branch, tag, remote-tracking branch, HEAD | .git/refs/、.git/packed-refs、.git/HEAD(or reftable) |
| Index (index/staging area) | Draft for "next commit": path → blob hash + file metadata | .git/index(binary file) |
| working tree | The normal file you see in the editor | Repository root directory |
porcelain and plumbing
Git commands are divided into two categories (these names come from "the porcelain surface and pipes of the toilet"):
| porcelain (high-level) | plumbing (bottom layer) | |
|---|---|---|
| For whom | people | Scripts, tools, people who want to see the principles clearly |
| Example | add、commit、status、log、switch、push | hash-object、cat-file、ls-tree、ls-files、update-index、write-tree、commit-tree、update-ref、rev-parse、for-each-ref |
| Output stability | May vary with version, language, configuration (color, paging) | The format is stable and suitable for parsing |
| Script suggestions | Use when needed--porcelainand other machine-readable options (e.g.git status --porcelain=v2) | First choice |
Note the counter-intuitive naming:git status --porcelainrefers to "a stable format for porcelain scripts", which happens to be machine-readable.
When: When will you still encounter centralized
- Perforce (Helix Core) is still commonly used by teams such as games and chip design that contain a large number of non-mergeable binary assets, which requires file exclusive locks. The Git-side counterpart is file locking for Git LFS (Lesson 6).
- Old TFS/Azure DevOps projects may still use TFVC; Microsoft's official recommendation is that new projects use Git and provides a TFVC → Git import tool (Lesson 3).
Comparison with similar technologies
| Git | SVN | TFVC | Mercurial(hg) | |
|---|---|---|---|---|
| model | Distributed | Centralized | Centralized | Distributed |
| local history | complete | None (working copy only) | None (server/local workspace two modes) | complete |
| branch | Pointer to commit, extremely cheap | Directory copy (/branches/x, cheap server-side replication) | Server side path branch | Named branches + bookmarks (similar to Git branches) |
| Commit ID | Content hash (SHA-1, optional SHA-256) | Globally incremented revision number r1234 | Change set number | Hash + local serial number |
| Staging area | Yes (index) | None | There is a "pending changes" list | None (available extensions) |
| Permission granularity | Repository level (the platform can do branch protection) | Can be authorized by directory | Can be authorized by path | repository level |
| Current situation | de facto standard | Still under maintenance, stock project | Azure DevOps is still supported, new projects recommend Git | Still under maintenance; Bitbucket ended support in 2020 |
--depthor partial clone--filter(Lesson 5, 6).Architecture diagram: centralized vs distributed
Data model diagram: snapshot and blob reuse (myapp real hash)
Interactive simulator: After the network is disconnected, what can centralized and distributed systems do?
First toggle the "Network" switch, and then click below to operate. On the left is the SVN working copy, and on the right is the Git clone; the terminal displays the real commands and typical output of both sides. Core mechanism: Git’s log/diff/commit/branch only reads and writes locally.git, only fetch/pull/push uses network protocols (Git transport protocol v2 over SSH or HTTPS).
Core commands and parameters
| command | function | Key parameters/description |
|---|---|---|
git --version | View version | Troubleshooting first step; Git in CI images is often older |
git help -a / git help -g | List all commands/concept guide | git help glossary、git help everyday |
git init | Create new repository | -b main、--bare、--object-format=sha256、--ref-format=reftable |
git clone URL | Copy the complete repository (full history) | --depth 1(shallow clone),--filter=blob:none(Partial Cloning, Lesson 6) |
git rev-parse | Parse names into hashes (plumbing) | HEAD、v1.0.0^{tree}、--show-toplevel、--git-dir、--show-object-format |
git ls-tree | List tree contents (plumbing) | -rrecursion,--abbrev、--name-only |
git status --porcelain=v2 | machine-readable status | Replacement of human formatting in scripts |
cd ~/git-lab/myapp
git rev-parse --show-toplevel --git-dir --show-object-format
git rev-parse v1.0.0 v1.0.0^{commit} v1.0.0^{tree}
/home/azureuser/git-lab/myapp .git sha1 be2b4d23bc95ecf094e6c9a9c28ccf32bb56b901 ee0355b8fc3f57113fa8b928616aa23bf39093f3 63777b90d98b75904bc6ea350a3fc6d0d35c5e88
How to read:v1.0.0itself resolves tolabel objectbe2b4d2 (note labels are independent objects);^{commit}Peel to the commit it points to ee0355b;^{tree}Then go to the root tree of the commit.Common mistakes:In PowerShell{}It has special meaning and needs to be quoted:git rev-parse 'v1.0.0^{tree}'。
# Snapshot reuse: In the two trees v1.0.0 and v1.1.0, the unmodified files point to the same blob diff <(git ls-tree v1.0.0) <(git ls-tree v1.1.0)
5c5 < 100644 blob 83e466e2a7df27f5fd20742866253c1b2e3b8b85 app.py --- > 100644 blob 838439b900b032de0adcca4dbdc2493091601ded app.py 7a8 > 100644 blob 19c1cdd7b5b8da3ba347ab30d90c7e5214c7485c settings.env
The only difference between the two versions isapp.pyChanged the blob, there are moresettings.env;The hashes of the remaining 6 files are exactly the same, and there is only one copy of each in the object library.Production use:In CI, you can directly compare subtree hashes to determine "whether a directory has changed":git rev-parse HEAD:src with HEAD~1:srcAre equal, much faster than file-by-file diff.
# porcelain vs plumbing: two outputs of the same information git status # Show to others: There is a prompt, which is affected by the language and color settings. git status --porcelain=v2 --branch # Give the script: the format is stable
# branch.oid f4ac97b045741bd4b587553d05e81bb3e10594ff # branch.head main # branch.upstream origin/main # branch.ab +0 -0
Experiment 1: "Seeing" Snapshots with the Plumbing Command (~4 minutes)
~/git-lab/myapp。cd ~/git-lab/myapp git ls-tree 9c56b83 git ls-tree 0cbdc7a
100644 blob 01f7a1619231f2d188659e6c4f68c01af133a552 README.md 100644 blob 5e06d0719bdeb62b363bf50985016b0dc433511a Dockerfile 100644 blob 01f7a1619231f2d188659e6c4f68c01af133a552 README.md 100644 blob 83e466e2a7df27f5fd20742866253c1b2e3b8b85 app.py 100644 blob 43620621daabb465d8b47528a6c3f0b5c1144086 compose.yaml 100644 blob 736990a001513d37919eebe7350588c9cad0e0be requirements.txt
The third commit's tree contains all 5 files - not just "this new Dockerfile and compose.yaml". The hash of README.md is exactly the same as commit 1.
for c in $(git rev-list --all); do git ls-tree -r $c; done | awk '{print $3, $4}' | sort | uniq -c | sort -rn | head -5
11 736990a001513d37919eebe7350588c9cad0e0be requirements.txt
11 01f7a1619231f2d188659e6c4f68c01af133a552 README.md
10 5e06d0719bdeb62b363bf50985016b0dc433511a Dockerfile
10 43620621daabb465d8b47528a6c3f0b5c1144086 compose.yaml
9 efdba87644caa4c6b045ebabf8fc429b75a28fb5 .gitattributes
There are a total of 12 local commits: the blob of README.md is referenced by 11 of the snapshots (only the last commit of feature/login has changed the README), but there is only one copy in the object library. If you have fetched a teammate's commit or made your own commit, the count will be different.
git switch -c lab/rename git mv compose.yaml docker-compose.yaml git commit -m "chore: rename compose file" git ls-tree HEAD | grep compose git log --oneline --follow --stat -- docker-compose.yaml | head -8
100644 blob 43620621daabb465d8b47528a6c3f0b5c1144086 docker-compose.yaml … chore: rename compose file compose.yaml => docker-compose.yaml | 0 …
In the new tree, it's just "the same blob with a different name."=>is log when comparing two snapshotsinferencename change (content similarity ≥ 50% is considered a name change).
git remote set-url origin /nonexistent), executegit log、git diff v1.0.0 v1.1.0、git commit --allow-empty -m testAll successful;git fetchfailed. When finished, change it back to:git remote set-url origin ~/git-lab/remote/myapp.git。git switch main git branch -D lab/rename
Case 1: SVN → Git migration, the team thought “history was lost”
Question:A 10-year-old SVN repository (trunk/branches/tagsAfter the layout) was moved to Git, developers found that every "tag" became a branch, and some people complained that clone was too slow.Method:use git svn clone --stdlayout --authors-file=authors.txt(or a specialized migration tool) to complete author mapping;refs/remotes/origin/tags/*Convert to real Git tags; move large binary files into Git LFS (Lesson 6).Configuration:SVN writes are frozen before migration, and SVN reads are retained for half a year after migration.Limitations:SVN's per-directory authorization has no counterpart in Git - one needs to tear down the repository or use the platform's CODEOWNERS + branch protection (Lesson 3).
Case 2: Server crashed, distributed architecture saved data
Question:The disk of the self-built Git server is damaged, and the last backup was 3 days ago.Method:Because every developer and CI runner clone contains the full history, findgit fetchThe latest machine,git push --mirrorGo to the new server to restore all branches and tags.Limitations:Only references that have been fetched by a clone can be restored; PR discussions, Issues, Wikis, branch protection rules, etc.Platform dataNot in Git, requires a backup of the platform itself.
Case 3: Script parsing git status error after upgrade
Question:For deployment scriptsgit status | grep "nothing to commit"To determine whether the workspace is clean, it will always be judged as "changed" on a machine with a Chinese language environment.Method:Use plumbing / stable format instead:test -z "$(git status --porcelain)", orgit diff --quiet && git diff --cached --quiet。Limitations:The two writing methods handle untracked files differently:--porcelainUntracked files will be listed (??),diff --quietThey will be ignored.
Common errors and solutions
git: command not found / 'git' is not recognized as an internal or external command
Reason:Not installed, or PATH not refreshed after installation (Windows needs to reopen Terminal).
which -a git || command -v git echo $PATH
Fix:Install by module 0; Windows reopen the terminal or use Git Bash; macOS if only/usr/bin/gitAndxcode-selectIf it is not installed, a prompt to install Command Line Tools will pop up.
git --version still shows 2.43.0 (PPA has been installed)
Reason:After adding the PPA, theapt update, or the shell caches the old path, or there is still one on the machine/usr/local/bin/git。
apt policy git which -a git hash -r
Fix:apt policy gitThe mid-candidate version should be fromppa.launchpadcontent.net/git-core;Executesudo apt install --only-upgrade git。
fatal: ambiguous argument 'v1.0.0^{tree}': unknown revision or path not in the working tree.
Reason:In PowerShell or zsh^、{}Interpreted by the shell; or the label does not exist.
Fix:Add single quotes:git rev-parse 'v1.0.0^{tree}'; usegit tag -lConfirm that the label exists; add at the end of the command--Distinguish between versions and paths.
The output of git status in the script is different on different machines
Reason:The human-readable output of the porcelain command varies with the language (LANG), color,status.shortWait for configuration changes.
Fix:use git status --porcelain=v2、git rev-parse、git for-each-ref --formatWait for a stable interface; when necessaryLC_ALL=C git …。
1. A command to output the blob hash of app.py in v1.1.0.
git rev-parse v1.1.0:app.py # 838439b900b032de0adcca4dbdc2493091601ded
2. Determine in the script whether the workspace and staging area are completely clean (including untracked files).
if [ -z "$(git status --porcelain)" ]; then echo clean; else echo dirty; fi
After the team moved from TFVC to Git, someone said, "I only change one file at a time. Why does Git save a snapshot of the entire project? Isn't it a waste of space?" What's your answer?
Snapshots are just data models: unmodified files refer to existing blobs in the new tree and are not stored repeatedly; what is added in each commit is only the new blob of the modified file, several modified trees on the path, and a commit object. andgit gcSimilar objects are delta compressed when packaging, and the actual usage is often smaller than the server storage of a centralized system. The advantage of the snapshot model is that it is fast to switch versions and compare any two versions, and it also makes branching and merging easier.
Verified instructional videos
Official documentation
- Pro Git 1.1 About Version Control
- Pro Git 1.3 What is Git?(Snapshots, Not Differences)
- Pro Git 10.1 Plumbing and Porcelain
- git(1) command classification (High-level / Low-level commands)
Video storyboard (approximately 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Picture: The central server and three laptops, the network cable is disconnected, and the log command on the left laptop displays a red error.
Narrator: In centralized version control, only the server has the complete history. If the network is disconnected, you cannot view the history or commit.
Screen: Each of the three laptops carries a complete .git cylinder, and can still commit and branch when the network is disconnected.
Narrator: Git is distributed, and each clone is a complete repository. origin is just a copy of the team's agreement.
Screen: Three commits are arranged in sequence, with a complete tree underneath each commit. The README squares are connected to the three trees with the same color.
Narrator: Each commit is a snapshot of the entire project; files that have not been changed are reused directly from the same blob, and only one copy is saved.
Screen: The upper "tiles" say add, commit, push, and the lower "pipe" says hash-object, cat-file, update-ref.
Narrator: People use the porcelain command, scripts use the plumbing command. In the next module, we will use plumbing to disassemble Git objects.
Module 2 · Object model: blob, tree, commit, ref
- Tell what the four types of objects (blob, tree, commit, annotated tag) store, who points to whom, and be able to draw the object diagram of myapp repository v1.0.0.
- Understand object ID =
SHA-1("< type > < bytes >\0" + content), can usegit hash-objectwithsha1sumManual verification; aware of the current state of SHA-256 repositories and plans for Git 3.0. - Skilled use
git cat-file -t/-p/-s、git ls-tree、git rev-parse, understand.gitUnderstand the role of each entry in the directory, and understand the relationship between loose objects and packfiles.
What: four types of objects + references
| Object type | What to save | point to | Example in myapp |
|---|---|---|---|
| blob | bytes of file content,No file name, no permissions | — | 01f7a16= Contents of README.md |
| tree | A directory: several itemspattern type hash name | blob (file), tree (subdirectory), commit (submodule) | 63777b9= root directory of v1.0.0 |
| commit | Root tree, 0 or more parents, authors, committers, commit information (can be signed) | 1 tree + parent commit | ee0355b(v1.0.0 points to it) |
| tag(with annotation label) | Target object, target type, tag name, tagger, description (can be signed) | Usually commit | be2b4d2= tag object v1.0.0 |
Reference (ref)Not an object, but a mutable pointer to name → hash:refs/heads/main(branch),refs/tags/v1.0.0(label),refs/remotes/origin/main(remote-tracking branch), andSymbol reference HEAD(The content is usuallyref: refs/heads/main)。lightweight tagsJust a ref pointing to commit, no tag object is created;Notes label(git tag -a) will create a tag object to record who and when the tag was tagged. Annotation tags should be used when publishing.
Why: Why should we name it by content hash?
- Remove duplicates: Same content → same ID → only one copy is saved (blob reuse of module 1).
- integrity: commit contains the hash of tree, tree contains the hash of blob, and parent contains the hash of the previous commit - this is a treeMerkle tree / hash chain. If any byte in the history is changed, the hashes of all subsequent commits will change, so "rewriting history" will definitely generate a new commit ID in Git (rebase and filter-repo in Lessons 2 and 7 are based on this).
- immutable: Once written, the object will not be modified; "modification" is always writing a new object + moving the ref.
How: Calculation and storage of object IDs
- Construct the header:
"blob 86\0"(type, spaces, content bytes, NUL bytes). - SHA-1 is calculated on the "header + content", resulting in a 40-bit hex ID (64-bit for SHA-256 repositories).
- Compress "head + content" with zlib, write
.git/objects/Below, the first 2 digits of the ID are the directory and the last 38 digits are the file name.loose object:.git/objects/01/f7a1619231…。 git gc(or automatic maintenancegit maintenance) packs the loose object intopackfile(.pack+.idxIndex +.revreverse index), and dodelta compression;Network transmission (clone/fetch/push) is also based on packfile.
SHA-1, SHA-256 and Git 3.0
- Git default is stillSHA-1, and has built-in SHAttered collision attack detection (SHA-1DC, used by default since 2.13), so known collision attack techniques will be identified.
- SHA-256The repository is now available:
git init --object-format=sha256; usegit rev-parse --show-object-formatView. Limitations: SHA-1 and SHA-256 repositories cannot directly fetch/push each other. Some hosting platforms and tools still have incomplete support for SHA-256 (subject to the documentation of each platform). - Git 3.0 (planned): The official BreakingChanges document lists - newly initialized repositorys use SHA-256 by default (provided the ecosystem is ready;There are no plans to deprecate SHA-1), the default reference storage is changed from files toreftable, the default branch name is changed to
main, Rust becomes required, etc. The documentation states 3.0No confirmed release date yet。
When: When do you need to look at the object directly?
- Check "Which commit does this tag point to" and "What is the content of this file in a certain version":
git cat-file -p v1.0.0、git show v1.0.0:app.py。 - Understand the side effects of reset / rebase / amend: they all just create new objects and move refs, the old objects are still there and can be retrieved via the reflog (Lesson 7).
- When writing CI scripts, compare subtree hashes, obtain the last modified commit of a certain path, etc.
Comparison with similar technologies
| Git object library | Docker Image Layer (Docker Lesson) | SVN | |
|---|---|---|---|
| Addressing mode | Content Hash (SHA-1/SHA-256) | content hash(sha256: digest) | revision number + path |
| Deduplication granularity | File (blob) and directory (tree) | Layer (tar package) | Server side delta |
| variable name | refs (branch, tag) | tag(myapp:1.0) | path |
| Immutable ID | commit hash | mirror digest | Revision number |
Object graph: v1.0.0 of myapp (all real hashes)
Storage graph: a blob from content to disk
Object graph browser: click on any object to view the real output of git cat-file
Start at ref and follow the pointer: tag → commit → tree → file, or follow parent back to the first commit. Each node displaysgit cat-file -t(type),-s(size) vs.-p(Content) - All hashes and outputs are from the practice repository, you can verify them one by one in the terminal. You can also click "Auto Roam".
Core commands and parameters
| command | function | Key parameters/description |
|---|---|---|
git cat-file -t OBJ | Object type | blob / tree / commit / tag |
git cat-file -p OBJ | Beautify print content by type | tree is displayed as a list;-sdisplay size;-eJust check if it exists (exit code) |
git cat-file --batch-check | Batch query (script) | --batch-all-objectsList all objects |
git hash-object FILE | Calculate blob ID | -wWrite to object library;--stdin;-t tree |
git ls-tree TREE-ISH | List trees | -r、-l(display size),--name-only |
git rev-parse REV | name → full hash | HEAD~2、main^2、v1.0.0^{}、HEAD:path、--short |
git show-ref / git for-each-ref | list all citations | --format='%(refname) %(objectname:short) %(objecttype)' |
git count-objects -vH | loose/pack object statistics | Determine whether gc is needed |
git verify-pack -v | View packfile contents and delta chain | The parameters are.idx File |
cd ~/git-lab/myapp git cat-file -t v1.0.0 # The note tag itself is an object git cat-file -p v1.0.0 git cat-file -p ee0355b # The commit pointed to by the label git cat-file -p 63777b9 # The root tree pointed to by the commit
tag object ee0355b8fc3f57113fa8b928616aa23bf39093f3 type commit tag v1.0.0 tagger Git Lab <lab@example.com> 1767276000 +0000 release 1.0.0 tree 63777b90d98b75904bc6ea350a3fc6d0d35c5e88 parent 0cbdc7a61fefd0f5abc7b33305983e04d5c050bd author Git Lab <lab@example.com> 1767272400 +0000 committer Git Lab <lab@example.com> 1767272400 +0000 chore: add .gitignore and .gitattributes 100644 blob efdba87644caa4c6b045ebabf8fc429b75a28fb5 .gitattributes 100644 blob 7616915e440278a4d2597cd32b44e8402421df18 .gitignore 100644 blob 5e06d0719bdeb62b363bf50985016b0dc433511a Dockerfile 100644 blob 01f7a1619231f2d188659e6c4f68c01af133a552 README.md 100644 blob 83e466e2a7df27f5fd20742866253c1b2e3b8b85 app.py 100644 blob 43620621daabb465d8b47528a6c3f0b5c1144086 compose.yaml 100644 blob 736990a001513d37919eebe7350588c9cad0e0be requirements.txt
How to read:The timestamp is Unix seconds + time zone (1767272400 = 2026-01-01 13:00 UTC). Patterns in tree:100644Ordinary documents,100755executable file,120000symbolic link,040000subdirectory (type tree),160000submodule (type commit). Git only records "whether it is executable", not full Unix permissions.
Manually calculating object IDs
printf 'hello git\n' | git hash-object --stdin
printf 'blob 10\0hello git\n' | sha1sum # Header "blob 10\0" + content, the same result
git hash-object README.md # Consistent with the hash of README.md in tree
python3 -c "import zlib;print(zlib.decompress(open('.git/objects/01/f7a1619231f2d188659e6c4f68c01af133a552','rb').read()))"
8d0e41234f24b6da002d962a26c2495ea16a425f 8d0e41234f24b6da002d962a26c2495ea16a425f - 01f7a1619231f2d188659e6c4f68c01af133a552 b'blob 86\x00# myapp\n\nA tiny Flask + Redis hit counter used throughout the Docker and Git courses.\n'
Common mistakes:Just cloned or executedgit gcThe objects in the repository have been packaged,.git/objects/01/…The file does not exist - use this timegit cat-fileJust read (it looks for both loose objects and packfiles). If on Windowscore.autocrlf=true, the workspace file is CRLF,git hash-object README.mdWill press first.gitattributesThe /autocrlf rule is converted to LF and then calculated, so the result is still consistent with the repository;sha1sumReading the file directly does not.
SHA-256 repository and reftable experience
cd /tmp git init -q --object-format=sha256 demo-sha256 printf 'hello git\n' | git -C demo-sha256 hash-object --stdin git -C demo-sha256 rev-parse --show-object-format git init -q --ref-format=reftable demo-reftable ls demo-reftable/.git/reftable
0cee7efe07c21236b086b48ae6219ee4f894e991da7faaf821aa1601faade115 sha256 0x000000000001-0x000000000001-5ebcc0d4.ref tables.list
For the same content, the ID in the SHA-256 repository is 64 bits. reftable stores all references into a binary table file (the random suffix in the file name is different each time), which makes reading and writing faster when a large number of references occur, updates are atomic, and avoids branch name conflicts on case-insensitive file systems.Production use:At present, most hosting platforms still use SHA-1 repositorys. Production repositorys should not use SHA-256 rashly until the platform clearly supports it. Cleanup:rm -rf /tmp/demo-sha256 /tmp/demo-reftable。
.git directory structure
| entry | function |
|---|---|
HEAD | Current location:ref: refs/heads/main, or directly the hash when detached |
config | Repository-level configuration (remote, branch upstream, etc.) |
objects/ | Object library:xx/loose object underpack/packfile underinfo/ |
refs/heads/ · refs/tags/ · refs/remotes/ | Branches, tags, remote-tracking branches (one ref per file) |
packed-refs | Packed reference (appears after gc);^The first line is the commit with the annotation tags stripped off |
index | Staging area (binary, module 3) |
logs/ | reflog: Movement log for each ref (safety net for module 5) |
hooks/ | Client hook example (*.sample, Lesson 5) |
info/exclude | Ignore rules that only take effect for this repository and are not committed (Module 8) |
COMMIT_EDITMSG · ORIG_HEAD · FETCH_HEAD · MERGE_HEAD | Last commit information, HEAD before dangerous operation, last fetch result, merge in progress mark |
description | For GitWeb use only and can be ignored |
cd ~/git-lab/myapp # The above demonstration cd to /tmp, first return to the practice repository
cat .git/HEAD
cat .git/refs/heads/main 2>/dev/null || grep refs/heads/main .git/packed-refs
git count-objects -v | head -2
git gc -q && git count-objects -vH
git verify-pack -v .git/objects/pack/*.idx | grep -E '^[0-9a-f]{40} (blob|tree|commit|tag)' | awk '{print $2}' | sort | uniq -c
ref: refs/heads/main
f4ac97b045741bd4b587553d05e81bb3e10594ff
count: 41
size: 164
count: 0
size: 0 bytes
in-pack: 41
packs: 1
size-pack: 6.13 KiB
prune-packable: 0
garbage: 0
size-garbage: 0 bytes
15 blob
12 commit
2 tag
12 tree
41 = 12 commits + 12 trees + 15 blobs + 2 tag objects. After gc, the number of loose objects is 0, and they all enter a packfile of about 6 KiB; refs are also packed intopacked-refs, so.git/refs/heads/mainThe file may no longer exist -Do not read ref files directly in scripts, want to usegit rev-parse。
Experiment 2: Construct a commit by yourself (without add and commit, about 6 minutes)
~/git-lab/myapp, operate on a new branch.cd ~/git-lab/myapp git switch -c lab/plumbing
BLOB=$(printf '1.2.0\n' | git hash-object -w --stdin) echo $BLOB git cat-file -t $BLOB; git cat-file -p $BLOB
26aaba0e86632e4d537006e45b0ec918d780b3b4 blob 1.2.0
git update-index --add --cacheinfo 100644,$BLOB,VERSION git ls-files -s VERSION TREE=$(git write-tree); echo $TREE git cat-file -p $TREE | grep VERSION
100644 26aaba0e86632e4d537006e45b0ec918d780b3b4 0 VERSION d8df9cb6ea60f0138107c3e2f1fee1d9b7371046 100644 blob 26aaba0e86632e4d537006e45b0ec918d780b3b4 VERSION
The tree hash only depends on the directory content, so as long as your index is consistent with main plus VERSION, everyone will get the same tree hash (premise: your main is still in f4ac97b, and there is no pull teammate's commit).
COMMIT=$(echo "chore: add VERSION via plumbing" | git commit-tree $TREE -p HEAD) git cat-file -p $COMMIT git update-ref refs/heads/lab/plumbing $COMMIT git log --oneline -2 git status -s
tree … parent f4ac97b045741bd4b587553d05e81bb3e10594ff author Your Name <you@example.com> 1763197200 -0500 committer Your Name <you@example.com> 1763197200 -0500 chore: add VERSION via plumbing 3b1c9e2 (HEAD -> lab/plumbing) chore: add VERSION via plumbing f4ac97b (tag: v1.1.0, origin/main, main) Merge branch 'hotfix/redis-timeout' D VERSION
git status show D VERSION: There is VERSION in the repository and index, but there is no such file in the workspace - because we never created it on disk. executegit restore VERSIONIt can be retrieved from the index. These four steps (hash-object → update-index → write-tree → commit-tree → update-ref) are exactlygit add + git committhings to do.
git fsck --full 2>&1 | tail -3 git cat-file -e $COMMIT && echo "commit exists"
git restore VERSION 2>/dev/null; git switch main git branch -D lab/plumbing # The committed object is still in the library and becomes an "unreachable object", and will be cleaned up by gc later.
Case 1: "Sending the wrong version" in the release pipeline - lightweight tags vs. annotated tags
Question:For publishing scriptsgit tag v2.3.0(Lightweight tag) Later, someone re-tagged the same name locally and pushed it. There is no record indicating who moved the tag.Method:Specify publishing with only annotation (or signature) tagsgit tag -a v2.3.0 -m "…"; Used in CIgit cat-file -t v2.3.0The check type must betag; Turn on tag protection on the platform (Lesson 3).Limitations:Annotated taggers can be faked, and the real credibility comes from signed tags (Lesson 5).
Case 2: Investigation of repository volume surge
Question:Clone time increased from 10 seconds to 3 minutes.Method:git count-objects -vHsee size-pack 3 GiB; usegit rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | sort -k3 -n | tailFind the largest blob - Someone committed a 2 GB database export.Configuration:Add .gitignore for short term; use for long termgit filter-repoClear history (lesson 7) and introduce LFS (lesson 6).Limitations:Since snapshots are immutable, delete new commits of filesNoShrink the repository and the blob will still be in the history.
Case 3: Determine whether to build based on "whether the subdirectory changes" in CI
Question:Monorepo builds all 12 services on every commit.Method:Compare subtree hashes:[ "$(git rev-parse HEAD:services/api)" != "$(git rev-parse HEAD~1:services/api)" ]Just build the api.Limitations:Requires full parent commit (shallow clone--depth 1timeHEAD~1does not exist, this classic trap will be covered in Lesson 5).
Common errors and solutions
fatal: Not a valid object name 3a2e3f4
Reason:The object does not exist (misspelled, belongs to another repository, has not been fetched), or the abbreviation is too short and ambiguous.
git cat-file -e 3a2e3f4 && echo ok git rev-parse --disambiguate=3a2e
Fix:Use a longer prefix; firstgit fetch; usegit log --all --oneline | grepConfirm.
error: short object ID 5e9 is ambiguous
Reason:Multiple objects share this prefix. The length of the abbreviation displayed by Git by default will automatically increase with the size of the repository (core.abbrev)。
Fix:Use at least 7–12 bits; always use full hashes in scripts (git rev-parse)。
error: object file .git/objects/ab/cdef… is empty / fatal: loose object … is corrupt
Reason:There was a power outage, the disk was full, or the synchronization disk (OneDrive/Dropbox) interfered when writing the object.
git fsck --full
Fix:If there is a complete copy on the remote end, the easiest way is to re-clone; or delete the damaged empty object filegit fetchMake up for it. Do not put the repository in the synchronization disk. See Lesson 7 for details.
fatal: unable to read tree 63777b9… (shallow cloning or partial cloning)
Reason:Shallow clones do not contain earlier commits; partial clones (--filter=blob:none) downloads blobs on demand and cannot be read when offline.
Fix:git fetch --unshallow, or try again after connecting to the Internet; usegit rev-parse --is-shallow-repositoryjudge. Lessons 5 and 6 explained in detail.
fatal: mismatched algorithms: client sha1; server sha256
Reason:SHA-1 repositorys and SHA-256 repositorys cannot directly communicate with each other.
Fix:The object format is unified at both ends; SHA-256 repository requires platform support. SHA-1 is still the main method used in production.
1. Directly output the contents of app.py in the v1.0.0 version without switching branches.
git show v1.0.0:app.py # or git cat-file -p v1.0.0:app.py
2. List the 3 largest blobs (hash, size, path) in the repository.
git rev-list --objects --all \ | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' \ | awk '$1=="blob"' | sort -k3 -n | tail -3
Two developers created exactly the same content on their own machines.LICENSEFile and commit. Are their blob hashes the same? What about the commit hash?
blob hashSame: It only depends on "blob + length + content". The tree hash is also the same if the directory contents are consistent. commit hashdifferent: The commit content includes the author/committer’s name, email address, timestamp, and parent. Any difference will produce a different hash. This is why the module 0 script fixes the identity and time so that everyone gets the same hash.
Verified instructional videos
Official documentation
- Pro Git 10.2 Git Objects
- Pro Git 10.3 Git References
- Pro Git 10.4 Packfiles
- gitrepository-layout(5)
- hash-function-transition · BreakingChanges (Git 3.0 plan)
Video storyboard (about 100 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: The README text is preceded by "blob 86 \0", enters a funnel labeled SHA-1, and comes out as 01f7a16.
Narrator: The way Git names each object is by hashing the "type, length, and content." The same content gets the same name on any machine.
Screen: Seven blob cards are gathered together by a tree, with the file name and 100644 written on the tree.
Narrator: A blob only has content, not a file name. File names and permissions are recorded in the tree, which can also contain subtrees.
Screen: The commit card points to the tree and is connected to the previous commit with the parent arrow to form a chain; someone modifies the old blob and the entire chain turns red.
Narrator: commit points to the root tree and parent commit, forming a hash chain. If any byte is changed in the history, the hashes of all subsequent commits will be changed.
Screen: The yellow label main, v1.0.0 is attached to the commit like a sticky note, and HEAD points to main.
Narrator: Branches and tags are just sticky notes stuck to commits, called citations. HEAD tells Git which sticky note you are currently on.
Module 3 · Three areas: working tree, staging area, repository
- Explain clearly what is stored in the working tree, index (also known as staging area/cache), and repository (.git object library + refs), and what add/commit/restore transfers between them.
- understand
git statusLong format and short format (XYTwo columns of status codes), knowing which command to use for each line. - use
git add -pTo temporarily save only some modifications, usegit diff(workspace vs index),git diff --staged(index vs HEAD),git diff HEAD(Workspace vs HEAD) Check exactly what is going to be committed.
What: Three areas (including remote, a total of four locations)
| area | What to save | physical location | How to see |
|---|---|---|---|
| workspace working tree | The normal file you are editing | Repository root directory | ls, editor |
| Index / staging area index | "Full snapshot for next commit": per path → pattern + blob hash + stage number + file stat info (size, mtime, inode) | .git/index | git ls-files -s、git diff --staged |
| repository repository | All objects + refs (the commit pointed to by HEAD is the "last snapshot") | .git/objects、.git/refs | git log、git cat-file |
| Remote repository | Another repository (Module 7) | origin | git log origin/main |
Key understanding: An index is not a "change list" but a complete snapshot.When the commit is just completed, the index = the tree of HEAD,git ls-files -swill be listedallThe file is tracked, not empty.git addJust replace the corresponding entry in the index with the new blob hash.
Why: Why is there a staging area?
- Carefully organized commit: Bug fixes and format adjustments can be made at once, and can be committed in two times, so that each commit only does one thing (convenient for review, revert, and bisect).
- Partial staging: Multiple modifications in the same file, only commit a few of them (
git add -p)。 - Performance: The index caches the stat information of the file,
git statusJust compare stat, unchanged files don't need to be rehashed - fast even for large repositories. - Merge conflict workbench: When there is a conflict, the same path has three versions of stage 1/2/3 in the index (Lesson 2).
How: The real steps of add and commit
git add VERSION:Read file → press.gitattributes/autocrlf does clean filtering → calculation"blob N\0"+contentSHA-1 →immediatelywrite blob.git/objects→ Update.git/indexEntries for VERSION in (add new ones if necessary).git commit: Run hooks such as pre-commit → Recursively generate tree objects from indexes (equivalent togit write-tree, the existing subtree is directly reused) → Create a commit object (tree + parent=HEAD + identity + time + information, equivalent togit commit-tree) → update the branch ref pointed to by HEAD to the new commit (equivalent togit update-ref), and write reflog at the same time.
Because the blob is ingit addIt was written when it was added, so the content of "added but not committed was overwritten by reset --hard" can actually still be used.git fsck --lost-foundRetrieval (Lesson 7).
git status short form XY status code
| XY | X (index vs HEAD) | Y (workspace vs index) | Next step |
|---|---|---|---|
?? | Untracked: Not in the index and not ignored | git addor add .gitignore | |
A | Added and temporarily saved | None | can be committed |
M | Changes have been staged | None | can be committed |
M | None | Modifications not staged | git add / git restore |
MM | Part of it has been temporarily saved | Later there were modifications | Note: The version in the index is committed |
D / D | Workspace deletion is not staged / deletion is staged (git rm) | — | |
R | The name change has been temporarily saved (status is inferred from comparing snapshots) | — | |
UU | Merge conflict, both parties modify | Lesson 2 | |
!! | Ignored (only--ignoreddisplayed) | Module 8 | |
When: When to bypass the staging area
git commit -a: Automatic stagingTrackedCommit after file modifications and deletions (excluding untracked new files). Good for small changes, but you lose fine control.git commit path: Only commit the current content of the specified path, ignoring other staged content in the index.
Comparison with similar technologies
| Git | SVN | Mercurial | |
|---|---|---|---|
| Staging area | Yes, and it is a complete snapshot | None,svn commitCommit changes to the working copy directly (can be grouped by changelist) | None(hg commit -iinteractive selection) |
| Partial commit | add -p | by file | commit -i |
MMstatus). ② "The index is empty and will be cleared after commit" - the index is always a complete snapshot. ③ "git add just makes a mark" - add will write the blob object immediately. ④ "git commit -aNew files will be committed" - No, untracked files must firstgit add。Zone Map: What does the command move between zones?
Flowchart: Object written by git add + git commit (real hash)
Core animation: git add + git commit when index → tree → commit → move branch ref
Scene: in~/git-lab/myapp(main inf4ac97b) new inVERSION. Each step shows the status of the four locations at that moment, along with the plumbing command and real output that you can run in the terminal to verify (blob and tree hashes are the same for everyone; commit hashes depend on who you are and when).
Core commands and parameters
| command | function | Key parameters/description |
|---|---|---|
git status | Summary of differences among the three regions | -sshort form,-bbranch information,--ignored、-uno(Do not show untracked) |
git add PATH | Write blob + update index | -pinteractive chunking,-uOnly updated tracked files,-AAll (including deleted and new files),-N(intent-to-add)、--dry-run |
git diff | Workspace vs Index | --stat、--name-status、--word-diff、-w(ignore whitespace) |
git diff --staged | INDEX vs HEAD(=--cached) | One last check before commit |
git diff HEAD | Workspace vs HEAD | Contains all staged + unstaged edits |
git restore --staged PATH | Unstage (index ← HEAD) | Workspace remains unchanged |
git rm / git mv | Delete/rename and temporarily save | git rm --cached: Stop tracking but keep files |
git ls-files -s | View index content (plumbing) | --others --exclude-standard(not tracked),--debug |
cd ~/git-lab/myapp echo "DEBUG=true" >> settings.env # Modify, do not temporarily save sed -i 's/Hello from myapp!/Hello from myapp v1.2!/' app.py # macOS: sed -i '' git add app.py # staging echo "# tmp" > notes.txt # New file git status
On branch main Your branch is up to date with 'origin/main'. Changes to be committed: (use "git restore --staged <file>..." to unstage) modified: app.py Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: settings.env Untracked files: (use "git add <file>..." to include in what will be committed) notes.txt
How to read:The three paragraphs correspond to "Index vs HEAD", "Workspace vs Index" and "Not in Index" respectively. The prompts in brackets for each paragraph are the standard processing commands for that paragraph. The second line "up to date with 'origin/main'" is just the sumlocally recordedorigin/main comparison, not connected to the Internet (module 7).
git status -sb git diff # workspace vs index: only see settings.env git diff --staged # Index vs HEAD: only see app.py git diff HEAD --stat # workspace vs HEAD: both
## main...origin/main
M app.py
M settings.env
?? notes.txt
diff --git a/settings.env b/settings.env
index 19c1cdd..67eb686 100644
--- a/settings.env
+++ b/settings.env
@@ -1 +1,2 @@
REDIS_HOST=redis
+DEBUG=true
diff --git a/app.py b/app.py
index 838439b..1f195a1 100644
--- a/app.py
+++ b/app.py
@@ -9,7 +9,7 @@ redis = Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, socket_timeout=2
@app.route("/")
def hello():
count = redis.incr("hits")
- return f"Hello from myapp! I have been seen {count} times.\n"
+ return f"Hello from myapp v1.2! I have been seen {count} times.\n"
@app.route("/healthz")
app.py | 2 +-
settings.env | 1 +
2 files changed, 2 insertions(+), 1 deletion(-)
index 838439b..1f195a1It’s the blob hash before and after modification——1f195a1It is already in the object library (written when adding), you cangit cat-file -p 1f195a1View. Untracked notes.txt does not appear in any diffs.Common mistakes:thoughtgit diffEmpty means "no changes" - temporary changes will be used--stagedLook.
git add -p: only temporarily save some changes
git restore --staged app.py; git restore app.py settings.env; rm notes.txt # Return to clean state sed -i 's/Hello from myapp!/Hello from myapp v1.2!/; s/"status": "ok"/"status": "ok", "version": "1.2.0"/' app.py git add -p app.py # Enter s (split), y (temporarily store the first block), n (skip the second block) in sequence
@@ -9,9 +9,9 @@ redis = Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, socket_timeout=2
…
- return f"Hello from myapp! I have been seen {count} times.\n"
+ return f"Hello from myapp v1.2! I have been seen {count} times.\n"
…
- return {"status": "ok"}
+ return {"status": "ok", "version": "1.2.0"}
(1/1) Stage this hunk [y,n,q,a,d,s,e,p,?]? s
Split into 2 hunks.
@@ -9,8 +9,8 @@ …
(1/2) Stage this hunk [y,n,q,a,d,j,J,g,/,e,p,?]? y
@@ -13,5 +13,5 @@
…
(2/2) Stage this hunk [y,n,q,a,d,K,g,/,e,p,?]? n
| Button | meaning | Button | meaning |
|---|---|---|---|
y / n | Temporarily save/do not temporarily save this piece | s | Split the current block into smaller blocks (there must be unmodified lines between two modifications) |
a / d | All remaining blocks of this file are temporarily stored/skip all | e | Manually edit this section (the most detailed) |
q | Exit | j/J/k/K/g// | jump/search between blocks;?show help |
git status -s; git diff --staged --stat; git diff --stat
MM app.py app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
MM: The same file has both staged changes (greeting) and unstaged changes (healthz). nowgit commitOnly greetings will be committed.Production use:It is safer to split "bug fix" and "smooth refactoring" into two commits, review and revert.git restore -p、git reset -p、git stash -pUse the same interactive interface.
git restore --staged --worktree app.py # End of demonstration: Undo these changes, Lab 3 needs to be done again from a clean app.py
Experiment 3: Watch how the index changes (~5 minutes)
cd ~/git-lab/myapp git switch -c lab/index git status -s # No output git ls-files -s | wc -l # All 8 tracked files are in the index git ls-files -s app.py
8 100644 838439b900b032de0adcca4dbdc2493091601ded 0 app.py
sed -i 's/Hello from myapp!/Hello from myapp v1.2!/; s/"status": "ok"/"status": "ok", "version": "1.2.0"/' app.py git ls-files -s app.py # Only modify the workspace, the index remains unchanged: still 838439b git add -p app.py # s → y → n git ls-files -s app.py # The index is replaced with a new blob containing "only the first modification"
100644 838439b900b032de0adcca4dbdc2493091601ded 0 app.py … 100644 1f195a15… 0 app.py
the new blob in the index (1f195a1…) is neither the HEAD version nor the workspace version, but an intermediate version "containing only the first block of modifications" - this isMMmeaning.
git commit -m "feat: show version in greeting" git show --stat HEAD | head -8 git status -s #Remaining healthz modifications: "M app.py" git add app.py && git commit -m "feat: expose version in /healthz" git log --oneline -3
echo "1.2.0" > VERSION git diff --stat # Cannot see VERSION (untracked files do not participate in diff) git add -N VERSION # Only register "intended to add" without writing the content git diff --stat # Now you can see it and can use add -p to stage it block by block. git add VERSION && git commit -m "chore: add VERSION file"
git rm --cached settings.env git status -s # "D settings.env" and "?? settings.env" git restore --staged settings.env # Undo this step
git switch main git branch -D lab/index
Case 1: Bringing debugging code to production
Question:Developer git add .After commit, put the temporaryprint(password) and DEBUG=TruePush them together to trigger a security alarm.Method:Team agreement must be read before commitgit diff --staged; usegit add -pinstead ofgit add .;Add pre-commit hook to scan debug statements and keys (Lesson 5).Limitations:The hook can be--no-verifySkip, server-side push protection/confidential scanning is still required (Lesson 3).
Case 2: git status takes 8 seconds in a large repository
Question:With a monorepo of 200,000 files, status is very slow every time.Method:Index cache stat information can only reduce hash calculations, traversing the directory is still time-consuming. enablecore.fsmonitor=true(built-in file system monitor, Windows/macOS) andcore.untrackedCache=true, or usescalarOne-click configuration (Lesson 6).Limitations:The support of the built-in fsmonitor on Linux is subject to the official documentation, and the Watchman hook can be used.
Case 3: "I obviously changed it, why is there still the old code in CI?"
Question:Developer git addLater, I modified the file and directlygit commit, the version pushed is the version at the time of add.Method:Before commitgit status -shabit, seeMMbe alert; or usegit commit -vAlso see the diff to be committed in the editor.Limitations:commit -aThis problem can be avoided, but all changes to tracked files will be committed together.
Common errors and solutions
nothing added to commit but untracked files present (use "git add" to track)
Reason:The new file has not yet been indexed;git commit -aUntracked files will not be processed.
Fix:git add fileCommit later; if the file should not be committed, add .gitignore (module 8).
no changes added to commit (use "git add" and/or "git commit -a")
Reason:The workspace is modified, but the index is the same as HEAD.
git status -s git diff --stat
Fix:Firstgit add(oradd -p) and commit again.
warning: in the working copy of 'app.py', LF will be replaced by CRLF the next time Git touches it
Reason:End-of-line conversion tips:core.autocrlfor.gitattributes of textProperty requires CRLF when checking out.
Fix:Usually harmless. For team use.gitattributesUnify line endings (module 8); if every line of the entire file is displayed as modified, it is probably a line ending problem. Usegit diff --ignore-cr-at-eolorgit add --renormalize .processing.
Only binary files changed! No response when pressing s in / add -p (Sorry, cannot split this hunk)
Reason:Binary files cannot be split into chunks; there are no unmodified lines between two modifications and cannot be split further.
Fix:presseManually edit this section: delete the ones you don’t want to temporarily save+OK, put the ones you don’t want to temporarily store-Lines start with spaces.
fatal: Unable to create '…/.git/index.lock': File exists.
Reason:Another git process (IDE background, last interrupted command) is writing the index, or the lock file is left after the crash.
ps aux | grep -i [g]it
Fix:Remove the lock after confirming that there are no running git processes:rm -f .git/index.lock。
1. Move the staged app.py out of the stage, but keep the workspace modifications.
git restore --staged app.py #Old way of writing: git reset HEAD app.py
2. List all files that are not tracked and not ignored (suitable for scripts).
git ls-files --others --exclude-standard
You modified app.py in 3 places: fixing the null pointer, adjusting the log format, and deleting a comment. The reviewer wants the fix to be a separate commit for rollback. How to do it? How do I confirm that my commit is correct?
use git add -p app.pyOnly the repaired piece is temporarily saved (if necessary, usessplit oreedit) and thengit diff --stagedConfirmation only contains fixes,git diffConfirm that the remaining two places have not been temporarily saved, and thengit commit -m "fix: …";Then add the remaining modifications and commitstyle: / chore:. Use after commitgit show --stat HEAD~1 with git show HEAD~1Review.
Verified instructional videos
Official documentation
- Pro Git 2.2 Recording Changes to the Repository
- git-status Short Format
- git-add Interactive mode
- git-diff
Video storyboard (approximately 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: Three drawers side by side: workspace, index, repository; VERSION file appears in the first drawer.
Narrator: Git has three areas. What you edit is the workspace, the next committed draft is in the index, and the history is in the repository.
Screen: During git add, the file is compressed into a square marked 26aaba0 and dropped into the object library, and this number is written on the index card.
Narrator: git add doesn't just mark it, it immediately writes the contents into a blob and registers the hash into the index.
Screen: During git commit, the index card is "frozen" into a tree d8df9cb, then wrapped in a commit shell, and the main sticky note jumps from the old commit to the new commit.
Narrator: git commit turns the index into a tree, generates a commit object, and finally moves the branch pointer.
Screen: Three dotted lines mark git diff, git diff --staged, and git diff HEAD respectively.
Narrator: Remember which two areas the three diffs compare, and take a look at staged before committing, so that the debugging code will not be brought online.
Module 4 · Commit, view history and diffs
- Write a well-structured commit message (title ≤ 50–72 characters, imperative, blank lines, body explaining “why”) and learn about Conventional Commits
type(scope): subjectFormat and its use in automation. - Skilled combination
git logof--oneline --graph --decorate --all, scope syntaxA..B, filter parameters--author/--since/-- path, andgit show。 - use
git blameTo find the source of a certain line, usegit log -S(Change in the number of occurrences of a string) and-G(Regular matching lines have changed) Locate when a certain piece of code is added or deleted.
What: Criteria for a good commit
- atomicity: A commit only does one thing, can be independently reviewed and revert, and each commit can be built and passed (convenient
git bisect, Lesson 7). - Commit information: The first line is the title (recommended ≤ 50 characters, hard upper limit is about 72), using imperative mood ("Add..." "Repair..."), no period; one blank line; text descriptionwhyWhat are the side effects of changing? Wrap lines according to about 72 columns; you can add endnotes (trailer), such as
Refs: #123、Co-authored-by:、Signed-off-by:。
Conventional Commits 1.0.0 (Getting Started)
fix(api): set redis socket timeout to 2s Without a timeout, a hung Redis made every gunicorn worker block forever and /healthz never returned, so the load balancer kept routing traffic to dead pods. Refs: OPS-412
| type | meaning | Impact of semantic versioning (conventions of tools such as semantic-release) |
|---|---|---|
feat | new features | MINOR |
fix | fix defects | PATCH |
docs / style / refactor / perf / test / build / ci / chore | Documentation, formatting, refactoring, performance, testing, build, CI, miscellaneous | Usually no version is released (perf depends on configuration) |
feat!:or endnoteBREAKING CHANGE: | Incompatible changes | MAJOR |
The norm itself only enforcesfeat、fixand BREAKING CHANGE semantics, the remaining types come from community conventions (such as Angular conventions). Benefits: CHANGELOG can be automatically generated, version numbers automatically calculated, enforced in PR title checks (Lesson 5). The commit information of the practice repository myapp follows this format.
Why: History is the team’s “incident investigation report”
The code tells youwhat is now, history tells youWhy did it become like this. During online fault review, the three most frequently asked questions - "Who added this line, when and why?" "Which version did this configuration start from?" "What was changed between the two releases" - respectively correspond toblame、log -S/-G、log A..B。
How: log is "walking" on the commit graph
git logStarting from HEAD (or the given starting point), the commit graph is traversed along the parent pointer, and the output is output in reverse order of commit time by default;--allUse all refs as starting points;--graphDraw forks and merges in ASCII;--decorateThe annotation points to the refs of each commit (auto is turned on by default in the terminal and turned off in the pipeline);--first-parentMerge commits only follow the first parent (see mainline history).- range:
A..B= commits reachable from B but not from A ("What does B do more than A");A...B= symmetrical difference;^A BEquivalent toA..B。 git show OBJ:commit → metadata + diff with parent commit; tag → taginfo + target;REV:path→ File content.git blame: Backtrack line by line from the current file to find the commit that last modified each line (it compares the snapshot,-M/-CTrack code moving within/across files;--ignore-rev/blame.ignoreRevsFileMassive formatting commits can be skipped).git log -S string(pickaxe): list only the stringThe number of occurrences changescommit (i.e. addition or deletion);-G regular: List in diffMatching of added and deleted rowsCommit of the regular pattern (including only modifying the line containing the string).
When: Which tool to choose?
| question | command |
|---|---|
| Who was the last person to change this line? | git blame -L 6,6 app.py→ againgit show hash |
| The complete evolution of this function? | git log -L :healthz:app.py |
| When is a certain key/configuration item added and when is it deleted? | git log -S FAKE_SECRET --all |
| Which commits touched the line containing timeout? | git log -G 'timeout' -p -- app.py |
| What changed between releases? | git log --oneline v1.0.0..v1.1.0、git diff --stat v1.0.0 v1.1.0 |
| What PRs have been merged into the mainline? | git log --first-parent --oneline main |
Comparison with similar technologies
| Git | SVN | Hosting platform UI (GitHub/Azure Repos) | |
|---|---|---|---|
| View history | local git log, millisecond level | svn logRequires internet connection | The History/Blame view on the web page, the bottom layer is log/blame |
| Search history by content | log -S/-G | No built-in equivalent | Code searches usually only search the current version |
| line by line attribution | blame(Supports ignoring formatted commits) | svn blame | Blame view, partially supported.git-blame-ignore-revs |
git log -SIt takes a second to find it (experiment in this module), the key must be rotated and the history cleaned (lesson 7). ③ "git log"Displayed in chronological order" - the default is to sort by commit time. Branches may look staggered after merging; topological order is required.--topo-order. ④ "Just write 'fix' and 'update' in the commit message" - no one can understand it six months later.Commit Chart: A Complete History of the Practice Repository
Flowchart: from one line of suspicious code to full context
Interaction: git log parameter combinator
Check the parameters, and the terminal below will be displayed immediately.The newly generated practice repositoryThe real output of execution in Git (pre-run in Git). Observations:--allLet feature/login and experiment appear;--graphDraw forks and merges;--first-parent"Collapse" the hotfix branch into the merge commit;--decorateShow refs.
Core commands and parameters
| command | function | Key parameters/description |
|---|---|---|
git commit | Commit created by index | -m(can be multiple times, each is a paragraph),-v(Diff is displayed in the editor),--allow-empty、--trailer "Refs: X" |
git log | Traverse the commit graph | --oneline --graph --decorate --all、-n 5、-p、--stat、--author、--since/--until、--grep、-- path、--first-parent、--format |
git show | display object | --stat、REV:path、--name-only |
git blame | line by line attribution | -L start, stop、-L: function name、-w、-M/-C、--ignore-revs-file |
git log -S/-G | Search history by content | -S str(Changes in the number of occurrences),-G regex(change row matching), match-p --all |
git log -L | Track the evolution of a line or function | -L 6,6:app.py、-L :healthz:app.py |
git shortlog | Summary by author | -sn, release notes |
cd ~/git-lab/myapp git log --oneline --graph --decorate --all git log --pretty=format:'%h %ad %an %s' --date=short -5 git log --oneline v1.0.0..v1.1.0
f4ac97b 2026-01-01 Git Lab Merge branch 'hotfix/redis-timeout' abb417c 2026-01-01 Git Lab fix: remove FAKE_SECRET from settings.env bbc4ca6 2026-01-01 Git Lab config: add settings.env 985254d 2026-01-01 Git Lab feat: add /healthz endpoint 17f033d 2026-01-01 Git Lab fix: set redis socket timeout f4ac97b Merge branch 'hotfix/redis-timeout' abb417c fix: remove FAKE_SECRET from settings.env bbc4ca6 config: add settings.env 985254d feat: add /healthz endpoint 17f033d fix: set redis socket timeout
How to verify:v1.0.0..v1.1.0The 5 commits listed are the release notes material for 1.1.0.Suggested alias(Module 8):git config --global alias.lg "log --oneline --graph --decorate --all"。
git show bbc4ca6
commit bbc4ca63ddd65f6df124bc82ccee197ad953adc5
Author: Git Lab <lab@example.com>
Date: Thu Jan 1 17:00:00 2026 +0000
config: add settings.env
diff --git a/settings.env b/settings.env
new file mode 100644
index 0000000..ca5ff84
--- /dev/null
+++ b/settings.env
@@ -0,0 +1,2 @@
+REDIS_HOST=redis
+FAKE_SECRET=fake-9f8e7d6c-not-a-real-key
git blame -L 6,6 app.py git blame -L :healthz app.py git log --oneline -L6,6:app.py
17f033d1 (Git Lab 2026-01-01 15:00:00 +0000 6) redis = Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, socket_timeout=2)
985254d5 (Git Lab 2026-01-01 16:00:00 +0000 16) def healthz():
985254d5 (Git Lab 2026-01-01 16:00:00 +0000 17) return {"status": "ok"}
17f033d fix: set redis socket timeout
diff --git a/app.py b/app.py
--- a/app.py
+++ b/app.py
@@ -6,1 +6,1 @@
-redis = Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379)
+redis = Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, socket_timeout=2)
5e9d1b8 feat: add Flask app with Redis counter
diff --git a/app.py b/app.py
--- /dev/null
+++ b/app.py
@@ -0,0 +6,1 @@
+redis = Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379)
-L :healthzUse the function name to locate the line range (according to the language's funcname rules, Python's default rules can identifydef)。Common mistakes:Writing in Git Bash-L '/def healthz/,+1'time, with/The parameters at the beginning may be regarded as path conversion by MSYS, use:function nameor line number.
git log -S FAKE_SECRET --oneline --all git log -G 'socket_timeout' --oneline
abb417c fix: remove FAKE_SECRET from settings.env bbc4ca6 config: add settings.env 17f033d fix: set redis socket timeout
-SFound two commits adding (bbc4ca6) and removing (abb417c) secrets.Production use:Leak troubleshooting and confirming when a certain feature switch comes online.-SBy default, parameters are treated as ordinary strings; add--pickaxe-regexregarded as regular.
Experiment 4: Historical Investigation - FAKE_SECRET event review (about 6 minutes)
FAKE_SECRET". You need to answer: when it was introduced, who introduced it, which release tags it exists in, and whether it is still in HEAD now.cd ~/git-lab/myapp git grep -n FAKE_SECRET || echo "Not in the current version" git grep -n FAKE_SECRET $(git rev-list --all) | head -3
Not in the current version bbc4ca63ddd65f6df124bc82ccee197ad953adc5:settings.env:2:FAKE_SECRET=fake-9f8e7d6c-not-a-real-key
git log -S FAKE_SECRET --all --format='%h %an %ad %s' --date=iso
abb417c Git Lab 2026-01-01 18:00:00 +0000 fix: remove FAKE_SECRET from settings.env bbc4ca6 Git Lab 2026-01-01 17:00:00 +0000 config: add settings.env
git tag --contains bbc4ca6 git branch -a --contains bbc4ca6
v1.1.0 experiment feature/login * main remotes/origin/feature/login remotes/origin/main
Conclusion: The history of all branches from v1.1.0 and later contains this secret, and anyone who can clone the repository can see it. The correct response is:Rotate (invalidate) keys immediately, then press Lesson 7 to clean up the history and notify everyone to re-clone.
git switch -c lab/history echo "settings.env" >> .gitignore git add .gitignore git commit -m "chore(security): ignore settings.env" -m "Secrets must come from the environment or a vault, never from tracked files. FAKE_SECRET was rotated on 2026-11-15." --trailer "Refs: SEC-101" git log -1
chore(security): ignore settings.env
Secrets must come from the environment or a vault, never from
tracked files. FAKE_SECRET was rotated on 2026-11-15.
Refs: SEC-101socket_timeoutsource, and read out the commit message.git blame -L 6,6 app.py git show --stat 17f033d
git switch main git branch -D lab/history
Case 1: Automatically generate CHANGELOG and version number
Question:Handwritten release notes for each release are time consuming and missing.Method:The team uses Conventional Commits and uses commitlint to check the title in the PR; when releasing, it is based on semantic-release / release-please.feat/fix/BREAKING CHANGECalculate versions, generate CHANGELOG and label notes.Limitations:Rely on each commit (or PR title after squash) having the correct type; see Lesson 5 for toolchain details.
Case 2: blame loses meaning after large-scale formatting
Question:A commit after black/prettier was introduced changed every line, and the blame all pointed to "style: format code".Method:Write the complete hash of the commit to the root directory of the repository.git-blame-ignore-revs, local configurationgit config blame.ignoreRevsFile .git-blame-ignore-revs; GitHub's blame view will automatically recognize this file name.Limitations:Each developer needs to configure it locally once (can write bootstrap script).
Case 3: Accident review: What was changed between the two releases
Question:Error rates increased after v1.1.0 was released.Method:git log --oneline --first-parent v1.0.0..v1.1.0List the changes that were merged into the mainline,git diff --stat v1.0.0 v1.1.0Look at the scope of impact, lock the socket timeout changes in the hotfix, and then usegit showRead why.Limitations:If the team uses squash merge, the first-parent history is the PR list; when using merge commit, the merge commit information must include the PR number to facilitate traceability.
Common errors and solutions
Aborting commit due to empty commit message.
Reason:Save and exit without writing any information in the editor (or the editor returns immediately, for example, VS Code does not add--wait)。
Fix:git config --global core.editor "code --wait"; or use-m。
git log output stops at (END) / screen is occupied by pager, CI log stuck
Reason:Git uses paginator by default in terminalless。
Fix:pressqExit; singlegit --no-pager log;Set in scriptGIT_PAGER=catorgit config --global pager.log false(Git will not start the pager for non-terminal output).
fatal: your current branch 'main' does not have any commits yet
Reason:The new repository doesn't have any commits yet, and HEAD points to a branch that doesn't yet exist (the "unborn branch").
Fix:Complete the first commit first.
fatal: no such path 'app.py' in HEAD(blame / show)
Reason:The file has been renamed or deleted, or the relative path position is incorrect (not in the root directory of the repository).
Fix:git log --all --oneline -- '**/app.py'Find; use for older versionsgit blame old commit -- old path;git show REV:./relative path。
The Chinese in the commit information is displayed in git log as <E4><BD>... or garbled characters
Reason:Terminal encoding or less character set setting issues (most common in old Windows terminals).
Fix:Use Windows Terminal + UTF-8;git config --global core.quotepath false(Chinese file names are not escaped); when necessaryexport LESSCHARSET=utf-8。
1. List the commits that exist on main but not on feature/login.
git log --oneline feature/login..main
2. Find all the commits that have modified the Dockerfile and display the number of lines changed in each commit.
git log --oneline --stat -- Dockerfile
Online configuration itemsMAX_CONN=50was changed toMAX_CONN=500, causing the database connection to be exhausted. You only know that the configuration is inconfig/Directory. How to quickly find out which commit was modified and why?
git log -G 'MAX_CONN' -p -- config/List all commits that have changed lines containing MAX_CONN (-S MAX_CONNIt may not be found because the number of occurrences of the string has not changed, only the value has changed); orgit blameThe line in the current file directly gets the commit hash, and thengit show hashRead commit information and associated PR/ticket. Use when necessarygit revertRollback (Module 5).
Verified instructional videos
Official documentation
- Conventional Commits 1.0.0
- Pro Git 2.3 Viewing the Commit History
- git-log · git-blame · gitrevisions (scope syntax)
Video storyboard (approximately 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: Two pieces of commit information side by side, with "update" on the left and "fix(api): set redis socket timeout" plus text on the right.
Narrator: A good commit message explains why you changed it. Conventional commit allows machines to understand it: feat plus minor version, fix plus patch version.
Screen: Enter git log --oneline --graph --all in the terminal, and the committed image will be expanded like a subway line.
Narrator: log traverses the commit graph along the parent pointer, --all starts from all references, and --graph draws forks and merges.
Screenshot: A magnifying glass pans over lines of code, with blame marking the commit hash to the left of each line.
Narrator: blame tells you which commit was last modified for each line, and then use git show to read out the reason.
Screen: git log -S FAKE_SECRET hits two commits instantly, red alert.
Narrator: A pickaxe search can find when a string appears and disappears throughout history. Deleting a file does not delete the history.
Module 5 · Undo: restore, reset, revert
- Make it clear
git restore(recover files),git switch(switch branch) and "universal"git checkoutrelationship and know why new code should use the first two first. - accurate description
reset --soft / --mixed / --hardWhich branches, indexes, and workspaces pointed to by HEAD have been modified respectively, and know--hardRisks and hedging methods (reflog, ORIG_HEAD). - Use on "Pushed Commits"
git revertinstead ofreset; Correct usegit commit --amendModify the latest local commit.
What: Overview of undo tools
| command | Object of action | Modify HEAD/branch? | Modify index? | Modify workspace? | Rewrite history? |
|---|---|---|---|---|---|
git restore file | File | No | No | Yes(index → workspace, discard unstaged modifications) | No |
git restore --staged file | File | No | Yes (HEAD → index) | No | No |
git restore --source=REV -SW file | File | No | Yes | Yes | No |
git reset --soft REV | branch | Yes | No | No | Yes (local) |
git reset [--mixed] REV | branch | Yes | Yes | No | Yes (local) |
git reset --hard REV | branch | Yes | Yes | Yes (modifications that are not committed are lost directly) | Yes (local) |
git revert REV | Commit | Forward (add a reverse commit) | Yes | Yes | No |
git commit --amend | latest commit | Replace with new commit | — | — | Yes (local) |
Why: Why did Git 2.23 remove switch and restore?
git checkoutWear many hats:checkout branchSwitch branches (safe, uncommitted changes will be protected),checkout -- fileOverwrite workspace file with index (Not recoverablemodifications are discarded),checkout commitEnter detached HEAD. A command has both safe and dangerous semantics, which is a common reason for novices to accidentally delete code. Introduced in Git 2.23git switch(branch only) andgit restore(just files), they are no longer marked as experimental as of 2.51; official BreakingChanges documentation statescheckouthas been superseded by both, butAll three will remain。
| purpose | new command | old command |
|---|---|---|
| switch branch | git switch main | git checkout main |
| Create and switch | git switch -c feat | git checkout -b feat |
| Check out a commit (detached) | git switch --detach v1.0.0 | git checkout v1.0.0 |
| Discard workspace modifications | git restore app.py | git checkout -- app.py |
| Unstage | git restore --staged app.py | git reset HEAD app.py |
| Retrieve files from older versions | git restore --source=v1.0.0 app.py | git checkout v1.0.0 -- app.py(Change the index at the same time) |
How: reset only does three things (stop in sequence, stop in mode)
- Move the branch pointed to by HEADto target commit (
--softso far) - equivalent to "undo the commit, but the changes are still in the index". - Overwrite the index with the target committed tree(
--mixed, default, end here) - "Undo commit and add, modifications are still in the workspace". - Cover workspace with index(
--hard) - "Everything goes back to the target commit", uncommitted changesNo objects are backed up(Content that has not been added cannot be retrieved from Git).
The position before reset will be recorded inORIG_HEADand reflog(.git/logs/HEAD、.git/logs/refs/heads/main), soCommits that were resetavailablegit reset --hard ORIG_HEADorgit reset --hard HEAD@{1}Retrieval (Reflog explained in Lesson 7). There are also two safer variants:--keep(If local modifications will be overwritten, execution will be refused),--merge(used to abort a merge).
revert: offset old commits with new commits
git revert CCompute the reverse diff of C relative to its parent commit, apply it to the current HEAD and generate a new commit (infoRevert "…", the text contains "This reverts commit C."). History only increases but never decreases, it is appropriateAlready pushed, others may have already worked on itcommit. To undo a merge commit you need to use-m 1Specify which parent commit is the main thread (lesson 2).
amend: replace the most recent commit
git commit --amendCreate one with the current index and new informationnewCommit (new hash) with the same parent as the original commit and branch to it; the original commit becomes unreachable (still in the reflog). Suitable for correcting "missed files/wrong information written", but onlyNot pushedcommit.
When: Decision rules
| situation | Recommended |
|---|---|
| The workspace is messed up and I want to discard the changes to a certain file. | git restore file(Firstgit diff fileConfirm; orgit stashinsurance) |
| add wrong file | git restore --staged file |
| Just committed, wrong information/missing files,Not pushed | git add missing files; git commit --amend |
| Several recent local commits that I want to reorganize | git reset --soft HEAD~3and recommit (or Lesson 2’srebase -i) |
| All local experiments are cancelled. | git reset --hard origin/main(Firstgit status, when necessarygit stash -u) |
| CommitPushedto shared branch | git revert, never reset + force push (unless explicitly agreed by the team) |
Comparison with similar technologies
| Git | SVN | Kubernetes/Terraform (Following course) | |
|---|---|---|---|
| Discard local modifications | restore | svn revert | — |
| Undo published changes | revert(new commit) | reverse mergesvn merge -c -123 | kubectl rollout undoAlso "generate new version" instead of deleting history |
| rewrite history | reset/amend/rebase (local) | Basically not supported | — |
git revertwill restore the repository to that committed state" - no, it only offsetsthat oneCommitted changes; used to return to a certain staterestore --sourceor reset. ② “Nothing can be found after reset --hard”——Committedcan be retrieved from the reflog; only modifications that have not been added are actually lost (added ones are availablegit fsck --lost-foundFind blob). ③ "amend just changes the information" - it generates a new commit. If it has been pushed, it will fork with the remote end and force push is required. ④ "git restoreCan be undone" - it overwrites workspace files and has no recycle bin.Area map: The scope affected by the three reset modes
Commit diagram: The difference between reset and revert
Simulator: same starting point, different undo commands
Starting point: main has commit A → B → C; you modified it after Capp.pyand staged (index v4), then continued to modify the workspace (v5). Select a command and watch how the HEAD/branch, index, and workspace columns change, as well as the actual prompts in the terminal.
Core commands and parameters
| command | function | Key parameters/description |
|---|---|---|
git restore | Recover files | --staged(-S)、--worktree(-W, default),--source=REV、-p |
git switch | switch branch | -cNew,-Return to the previous one,--detach、--discard-changes |
git reset | Move branch + optional reset index/workspace | --soft、--mixed、--hard、--keep;git reset file= Cancel staging area |
git revert | reverse commit | --no-edit、-n(Only change the workspace without committing),-m 1(merge commit),A..B range |
git commit --amend | Replace recent commit | --no-edit、--reset-author、-m |
git reflog | HEAD/branch move records (safety net) | git reflog show main、HEAD@{2}、main@{yesterday} |
git clean | Delete untracked files | -n(Preview first!),-f、-d、-x(along with ignoring files) |
cd ~/git-lab/myapp && git switch -c lab/undo sed -i 's/Hello from myapp!/Hello from myapp v1.2!/' app.py git commit -am "feat: show version" git log --oneline -2 git reset --soft HEAD~1 && git status -s # Commit and revoke, the changes are still temporarily stored git reset HEAD && git status -s # Cancel the temporary save (--mixed)
55ff402 feat: show version f4ac97b Merge branch 'hotfix/redis-timeout' M app.py Unstaged changes after reset: M app.py M app.py
status code fromM (temporarily saved) becomes M(Unstaged): This is the difference between soft and mixed.How to verify:cat .git/ORIG_HEADShows the position before reset.
git commit -qam "feat: show version" git revert --no-edit HEAD git log --oneline -3 git reflog -6
[lab/undo 90adf23] Revert "feat: show version"
1 file changed, 2 insertions(+), 2 deletions(-)
90adf23 Revert "feat: show version"
f39ee4f feat: show version
f4ac97b Merge branch 'hotfix/redis-timeout'
90adf23 HEAD@{0}: revert: Revert "feat: show version"
f39ee4f HEAD@{1}: commit: feat: show version
f4ac97b HEAD@{2}: reset: moving to HEAD
f4ac97b HEAD@{3}: reset: moving to HEAD~1
55ff402 HEAD@{4}: commit: feat: show version
…
The reflog records every HEAD move, including 55ff402 "lost" by soft reset - it can stillgit show 55ff402、git branch rescue 55ff402. Reflog entries are retained for 90 days by default (30 days for unreachable ones,gc.reflogExpire/gc.reflogExpireUnreachable), andOnly exists locally, will not be pushed.
# Safe usage of --hard: preview what will be lost before executing git status -s git diff HEAD --stat git stash push -u -m "before hard reset" # Optional: stash everything first git reset --hard HEAD~1 git reset --hard ORIG_HEAD # Regret? Go back to before reset
HEAD is now at f39ee4f feat: show version HEAD is now at 90adf23 Revert "feat: show version"
#amend: Missing files/Change commit information (only not pushed) echo "1.2.0" > VERSION && git add VERSION git commit --amend --no-edit git commit --amend -m "chore: revert greeting and add VERSION" git log --oneline -2
Common mistakes:git clean -fdxwill be deleted.env、.venv/For local files that are ignored, be sure to firstgit clean -ndxPreview.Production use:CI runner is commonly used when reusing working directories.git clean -ffdx && git reset --hardKeep it clean (Lesson 5).
Experiment 5: Do each of the four undos once, and use reflog to check the details (about 7 minutes)
cd ~/git-lab/myapp git switch -c lab/undo2 main git log --oneline -1 # f4ac97b
echo "oops" >> Dockerfile; git add Dockerfile; echo "oops2" >> Dockerfile git status -s #MM Dockerfile git restore --staged Dockerfile; git status -s # "M Dockerfile" (both modifications are in the workspace) git restore Dockerfile; git status -s # clean git diff --quiet && echo "The workspace is clean"
echo "1.2.0" > VERSION git add VERSION && git commit -m "chore: add versoin" # Intentional misspelling OLD=$(git rev-parse HEAD) git commit --amend -m "chore: add VERSION file" git rev-parse HEAD; echo "Old commit $OLD is still accessible:"; git cat-file -t $OLD
(new hash) Old commits… are still accessible: commit
echo "important work" > notes.md && git add notes.md && git commit -m "docs: important notes"
git reset --hard HEAD~2 # Hand slip: two commits were withdrawn
git log --oneline -1 # Return to f4ac97b
ls notes.md VERSION 2>&1 | head -2
git reflog -4
git reset --hard HEAD@{1} # Return to before reset (ORIG_HEAD can also be used)
git log --oneline -3
HEAD is now at f4ac97b Merge branch 'hotfix/redis-timeout'
f4ac97b (HEAD -> lab/undo2, tag: v1.1.0, origin/main, main) Merge branch 'hotfix/redis-timeout'
ls: cannot access 'notes.md': No such file or directory
…
f4ac97b HEAD@{0}: reset: moving to HEAD~2
… HEAD@{1}: commit: docs: important notes
… HEAD@{2}: commit (amend): chore: add VERSION file
…
HEAD is now at … docs: important notesgit push -u origin lab/undo2 git revert --no-edit HEAD # Offset "docs: important notes" git push # Just push normally, no need for --force git log --oneline -3 origin/lab/undo2
echo "never added" > scratch.txt; echo "edit" >> app.py git reset --hard # The modifications to app.py are permanently lost; scratch.txt is not tracked, reset ignores it git status -s # Only "?? scratch.txt" remains git clean -n # Preview: Would remove scratch.txt git clean -f
git switch main git push origin --delete lab/undo2 git branch -D lab/undo2
Case 1: Friday night wrong launch – revert or reset?
Question:A commit that caused the 500 error was merged into main and deployed.Method:on maingit revert -m 1 < merge commit >(If squash is merged, directlygit revert < commit >), follow the normal PR process and go online; after fixing it on Monday, "revert the revert" or commit the fix.Configuration:main turns on branch protection and prohibits force push (lesson 3), fundamentally eliminating reset + force push.Limitations:After revert merges commits, if you merge the same branch again, Git will think that those commits have already been merged, and you need to revert that revert first (Lesson 2).
Case 2: Misusing checkout and losing an entire afternoon’s worth of code
Question:The developer wants to switch branches and entersgit checkout ., all uncommitted modifications are overwritten.Method:Git cannot retrieve the unadded content, so you can only turn to the IDE local history (VS Code Timeline / JetBrains Local History). The team then promoted theswitch/restore, and encourage "commit in small steps and stash at any time".Limitations:If the modification has beengit addYes, it can be usedgit fsck --lost-foundRetrieve from dangling blobs (Lesson 7).
Case 3: push rejected after amend
Question:The developer amends a commit that has been pushed to his own PR branch, and the push reportnon-fast-forward。Method:Available on personal branchgit push --force-with-lease(Only covered if the remote end is still in the state you last saw, than--forcesafety).Limitations:Don't do this on a shared branch; review comments on the PR platform may become "stale" as the commit disappears.
Common errors and solutions
error: Your local changes to the following files would be overwritten by checkout: app.py Please commit your changes or stash them before you switch branches.
Reason:Switching branches will rewrite app.py, and you have uncommitted changes - Git refuses to execute to protect your work (this is true for switch/checkout).
git status -s git diff app.py
Fix:commit, orgit stashThen switch togit stash pop;Use only after making sure you don’t want these modifications.git switch --discard-changes branch。
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Reason:The repository has only one commit (no HEAD~1), or the parent commit does not exist in a shallow clone.
Fix:Only one commit is used to undogit update-ref -d HEAD(Return to "no commit" state, modifications remain in the index); use for shallow cloninggit fetch --deepen=1。
error: commit f4ac97b is a merge but no -m option was given.
Reason:When revert merges a commit, Git doesn't know which parent commit to calculate the reverse diff against.
git cat-file -p f4ac97b | grep parent
Fix:git revert -m 1 f4ac97b(1 = mainline on which to merge).
"My commit is missing" after reset --hard
Reason:The branch pointer is moved away and the commit becomes unreachable but is still in the object store.
git reflog -10
git branch rescue HEAD@{1}
Fix:After finding the hash from refloggit reset --hard hashOr create a new branch to save. The reflog is only local and will disappear if you change the machine or delete the repository.
error: The following untracked working tree files would be overwritten by checkout
Reason:There is a tracked file in the target branch, and your workspace has an untracked file with the same name.
Fix:Remove or delete the untracked file (confirm the content first); orgit stash -u。
1. Undo the last 3 local commits and merge all their changes into a new commit.
git reset --soft HEAD~3 git commit -m "feat: combined change"
2. Only restore app.py to the version in v1.0.0 (update the index at the same time), without moving the branch.
git restore --source=v1.0.0 --staged --worktree app.py #Old way of writing: git checkout v1.0.0 -- app.py
you are on maingit reset --hard HEAD~2I wanted to throw away two local commits, but found that one of them had already been pushed to origin/main, and my teammates had already developed based on it. What should I do now?
Don't force push. Use firstgit reset --hard ORIG_HEAD(or in reflogHEAD@{1}) to restore to before reset to make the local consistent with origin; then usegit revert, push normally. The unpushed commit can be processed locally using reset/amend. Principle: Shared history can only be added but never modified.
Verified instructional videos
Official documentation
- Pro Git 7.7 Reset Demystified
- Pro Git 2.4 Undoing Things
- git-restore · git-switch · git-reset · git-revert
Video storyboard (about 100 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Image: A Swiss Army Knife of checkout is broken down into two specialized tools: switch and restore.
Narrator: checkout can both cut branches and overwrite files, so it is too easy to misuse. Now use switch to cut branches and restore files to restore them.
Screen: three columns, HEAD, index, and workspace; soft only lights up the first column, mixed lights up two columns, hard all three columns light up and the workspace turns red.
Narrator: reset does three things in sequence: move branches, reset indexes, and reset workspaces. Soft, mixed, and hard stop at the first, second, and third steps respectively.
Screen: Commit chain A B C, revert appends the reverse commit of C; reset pulls the main sticky note back to B, and C turns gray.
Narrator: Use revert for pushed commits, and the history will only increase but not decrease; reset will rewrite the history, and is only suitable for local use.
Screen: The gray C is relit by a line in the reflog list.
Narrator: Committed things are almost never lost, reflog remembers every place HEAD has been. Modifications that have never been added are truly irretrievable.
Module 6 · Getting Started with Branching and HEAD
- use
cat .git/HEAD、git rev-parse、git symbolic-refShow that branches are just movable pointers to commits and HEAD is a symbolic reference. - Explain "which pointer moves" when committing, and what Git does to the index and workspace when switching branches.
- Identify the detached HEAD state, know when to enter it, what are the risks of committing in it, and how to use it
git switch -cSave your work.
What: Branch, HEAD and detached HEAD
- branch =
refs/heads/<Name>, the content is a commit hash (under the files backend, it is a 40 hexadecimal character + newline = 41-byte text file; after packaging,packed-refsin; in binary tables under the reftable backend). Creating a branch = writing a new file, so almost zero cost. - HEAD= your "current location". Normally it isSymbol reference:
.git/HEADThe content isref: refs/heads/main, meaning "currently on the main branch". - detached HEAD (detached head pointer) =
.git/HEADThere is a commit hash written directly in it, which does not point to any branch. At this point you can view, compile, and even commit, but the new commits will not have any branches pointing to them.
Why: Why is it designed this way?
- Branches are just pointers → Creation, deletion, and renaming are all O(1), encouraging "one branch per task".
- HEAD points to the branch rather than the commit → when committing Git knows which branch to move: the new commit's parent = the commit pointed to by the current branch, thenMove only the current branch, other branches do not move.
- detached HEAD allows you to check out any historical version (tag, hash,
origin/main) to view or build without accidentally moving any branches.
How: What happens when commit and switch
- commit: read HEAD → parse to
refs/heads/main→ Newly committed parent = main current value → Updaterefs/heads/main;HEAD file itselfunchanged. Under detached HEAD, update directly.git/HEADhash in . - switch branch: Compare the tree of the current commit with the target commit → update the index and workspaceThere is a differencefiles (uncommitted modifications will be carried over if they do not conflict, and the switch will be refused if they conflict) →
.git/HEADChange toref: refs/heads/target→ write reflog(checkout: moving from A to B)。 - Enter detached:
git switch --detach v1.0.0orgit checkout v1.0.0/git checkout hash/git checkout origin/main; During the rebase and bisect processes, Git will also temporarily enter detached HEAD. - leave detached: Just cut to any branch. If commits are made in the detached state, Git will warn "leaving N commits behind". These commits can only be retrieved through reflog (they may be cleaned up by gc after being retained for 30 days by default).
Branch name rules (git check-ref-format)
available/layered (feature/login), but cannot contain spaces,~ ^ : ? * [ \、.., cannot be/or.lockThe ending cannot be@. files cannot exist at the same time under the backendfeature and feature/login(One is a file and the other is a directory); on the default case-insensitive file system of Windows/macOS,Feature with featureWill conflict - the reftable backend does not have these two problems.
When: When to use detached HEAD
- View/build/test a historical version or tag:
git switch --detach v1.0.0。 - CI systems usually check out a specific commit (detached), which is normal (Lesson 5).
- Need to be fixed on historical versions and retained: immediately
git switch -c hotfix/x。
Comparison with similar technologies
| Git branch | SVN branch | Mercurial | |
|---|---|---|---|
| essence | Pointer to commit (ref) | Directory copy on server | Named branches write metadata for each commit; bookmarks are similar to Git branches |
| Creation cost | Write a 41-byte file | Cheap server-side replication, but requires an Internet connection | bookmark is cheap |
| After deletion | The commit is still in (reflog/other branches) | Directories can be restored from history | Named branches are always in history |
Pointer map: HEAD → branch → commit
Flowchart: Fate of commits on detached HEAD
Branch pointer animation: commit/switch/detach
Click the command and observe which pointer moves in the commit graph..git/HEAD with refs/heads/*How the contents of the file change. Mechanism: commit only moves the branch pointed to by HEAD; switch only rewrites.git/HEAD(And update the index/workspace); when detached, commit directly rewrites.git/HEAD。
Core commands and parameters
| command | function | Key parameters/description |
|---|---|---|
git branch | List/create/delete branches | -v、-vv(including upstream),-a、-d(Deleted after merging),-D(mandatory),-m(rename),--merged、--contains |
git switch | switch branch | -c new branch [starting point]、-C(forced reset),-、--detach、--track origin/x |
git symbolic-ref HEAD | Which branch HEAD points to (plumbing) | detached reports an error;--short |
git branch --show-current | Current branch name | Output is empty when detached (script-friendly) |
git rev-parse --abbrev-ref HEAD | Current branch name | Output when detachedHEAD |
git check-ref-format --branch | Check whether the branch name is legal | Validate user input in script |
cd ~/git-lab/myapp cat .git/HEAD git symbolic-ref HEAD git rev-parse main git branch -vv
ref: refs/heads/main refs/heads/main f4ac97b045741bd4b587553d05e81bb3e10594ff experiment fd29861 wip: experiment with cache layer feature/login 912a321 [origin/feature/login] docs: document /login hotfix/redis-timeout 17f033d fix: set redis socket timeout * main f4ac97b [origin/main] Merge branch 'hotfix/redis-timeout'
*Indicates the current branch; the square brackets are upstream (module 7); hotfix and experiment only exist locally.How to verify that branches are just pointers:git update-ref refs/heads/demo f4ac97bA branch is "created" with the same effect asgit branch demoSame (aftergit branch -d demodelete).
git switch --detach v1.0.0 cat .git/HEAD git branch --show-current; git rev-parse --abbrev-ref HEAD git switch -
HEAD is now at ee0355b chore: add .gitignore and .gitattributes ee0355b8fc3f57113fa8b928616aa23bf39093f3 HEAD Previous HEAD position was ee0355b chore: add .gitignore and .gitattributes Switched to branch 'main' Your branch is up to date with 'origin/main'.
Note:git switch v1.0.0(without adding--detach) will be rejected:fatal: a branch is expected, got tag 'v1.0.0'——switch deliberately requires you to explicitly say "I want to enter detached". Andgit checkout v1.0.0It will enter directly and print the following long prompt:
Note: switching to 'v1.0.0'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by switching back to a branch. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -c with the switch command. Example: git switch -c <new-branch-name> Or undo this operation with: git switch - Turn off this advice by setting config variable advice.detachedHead to false HEAD is now at ee0355b chore: add .gitignore and .gitattributes
# Create a branch from a starting point, rename, delete git switch -c hotfix/1.0.1 v1.0.0 # Create a branch based on the tag (will not enter detached) git branch -m hotfix/1.0.1 hotfix/v1.0.1 git switch main git branch -d hotfix/v1.0.1 # Not merged but no new commits, can be deleted directly git branch --merged main # The branch that has been merged into main (safe to clean)
Common mistakes:git branch -d feature/loginnewspapererror: the branch 'feature/login' is not fully merged——Git protects unmerged commits and only uses them after confirming that they are not needed.-D。Production use:Clean regularly--mergedBranch; new in Git 2.56git branch --delete-merged, you can delete local branches that have been merged into their remote-tracking branches at once (new feature, use before usegit help branchMake sure your version supports it).
Lab 6: Fix old version and rescue commit on detached HEAD (~6 minutes)
cd ~/git-lab/myapp git switch --detach v1.0.0 git status | head -1 # HEAD detached at v1.0.0
sed -i 's/port=6379)/port=6379, socket_timeout=5)/' app.py git commit -am "fix: redis timeout for 1.0.x" cat .git/HEAD # Directly the hash of the new commit git log --oneline --decorate -2
a1b2c3d… a1b2c3d (HEAD) fix: redis timeout for 1.0.x ee0355b (tag: v1.0.0) chore: add .gitignore and .gitattributes
(HEAD)No branch name follows - this commit has no branch protection.
git switch main
Warning: you are leaving 1 commit behind, not connected to any of your branches: a1b2c3d fix: redis timeout for 1.0.x If you want to keep it by creating a new branch, this may be a good time to do so with: git branch <new-branch-name> a1b2c3d Switched to branch 'main'
git reflog -3
git branch hotfix/1.0.x HEAD@{1}
git log --oneline -2 hotfix/1.0.x
f4ac97b HEAD@{0}: checkout: moving from a1b2c3d… to main
a1b2c3d HEAD@{1}: commit: fix: redis timeout for 1.0.x
ee0355b HEAD@{2}: checkout: moving from main to v1.0.0git switch -c hotfix/1.0.x v1.0.0. Verify that HEAD is a symbolic reference:git switch hotfix/1.0.x && git symbolic-ref HEAD → refs/heads/hotfix/1.0.x。git switch main git branch -D hotfix/1.0.x
Case 1: "Current branch name" in CI is empty
Question:For build scriptsgit branch --show-currentGenerate image tags, get an empty string in CI, and the image is labeledmyapp:。Method:What CI checks out is the specific commit (detached HEAD). Use platform variables instead (GitHub ActionsGITHUB_REF_NAME、Azure Pipelines Build.SourceBranchName), or usegit rev-parse --short HEADas a label.Limitations:Platform variables have different meanings in PR builds (merged references), see Lesson 5 for details.
Case 2: Case conflict in branch names on Windows
Question:Someone pushed itFeature/Login, another person already hasfeature/login, ref lock error occurs when fetching on Windows.Method:The team unified lowercase naming and used a ruleset to restrict branch name patterns on the platform (Lesson 3); remove duplicate remote branches.Limitations:The files backend is filesystem affected; reftable (the planned default for Git 3.0) no longer has this issue.
Case 3: Maintain multiple release lines
Question:Requires maintenance of both 1.0.x and 1.1.x.Method:Create a long-term branch from a tagrelease/1.0(git switch -c release/1.0 v1.0.0), fix the advanced main, then cherry-pick to the release branch (Lesson 2), and thenv1.0.1label.Limitations:The more release lines there are, the higher the cost of backporting (Lesson 6 Branching Strategies).
Common errors and solutions
HEAD detached at v1.0.0 (git status first line)
Reason:You checked out a tag/commit/remote-tracking branch, or are in the process of rebase/bisect.
git status ls .git | grep -E "rebase|BISECT"
Fix:Just view →git switch -orgit switch main;There are new commits to keep →git switch -c new branch;rebase in →git rebase --continue/--abort(Lesson 2).
fatal: a branch is expected, got tag 'v1.0.0'
Reason:git switchOnly branch names are accepted.
Fix:git switch --detach v1.0.0, or create a branch based on tagsgit switch -c fix v1.0.0。
fatal: invalid reference: feature/logn
Reason:The branch name is misspelled, or the branch only exists remotely (the local branch has not been created yet).
git branch -a | grep -i log
Fix:if onlyorigin/feature/x,git switch feature/xTracking branches are automatically created (checkout.guessEnabled by default, module 7).
error: cannot lock ref 'refs/heads/feature/login': 'refs/heads/feature' exists; cannot create 'refs/heads/feature/login'
Reason:files in backendfeatureis a file and cannot be used as a directory.
Fix:Rename or deletefeatureBranch; remote residual usegit fetch --pruneClean up.
error: Cannot delete branch 'main' checked out at '/home/azureuser/git-lab/myapp'
Reason:The current branch (or branches checked out in other worktrees) cannot be deleted.
Fix:Firstgit switchto another branch; usegit worktree listView other working trees (Lesson 6).
1. Determine whether the current detached HEAD is in the script.
if git symbolic-ref -q HEAD >/dev/null; then echo "on branch $(git branch --show-current)"; else echo "detached at $(git rev-parse --short HEAD)"; fi
2. Create and switch to a new branch feature/healthz-v2 based on origin/main.
git fetch origin git switch -c feature/healthz-v2 origin/main
A colleague said: "I checked out a commit, changed something and committed it, and then switched back to main. Now the commit is gone. Was it deleted by Git?" Please explain the reason and give recovery steps.
Checking out a commit will enter detached HEAD, and the new commit is only referenced by HEAD; after switching back to main, there will be no ref pointing to it, sogit logNot visible, but the object is still in the library. Recovery:git reflogFind the hash of the line “commit: …”,git branch rescue hash(orgit switch -c rescue hash). By default, it can be retrieved within 30 days (the retention period of unreachable reflog entries), and may be cleaned up by gc afterwards. To commit in the detached state in the future, firstgit switch -c。
Verified instructional videos
Official documentation
- Pro Git 3.1 Branches in a Nutshell
- git-switch · git-branch
- git-checkout: DETACHED HEAD · git-check-ref-format
Video storyboard (about 80 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: The file manager opens .git/refs/heads/main, which contains only one line of 40-bit hash.
Narrator: A branch is a small file with just a commit hash written on it, so creating a branch takes almost no time.
Screen: The HEAD arrow points to main, and the main arrow points to commit; when committing, a new dot appears, and only main moves forward.
Narrator: HEAD points to the current branch. When committing, only the branch pointed to by HEAD is moved.
Screen: HEAD is pasted directly onto an old commit, the title turns red: detached.
Narrator: When a tag or hash is checked out, HEAD points directly to the commit. This is called a detached head pointer.
Screen: The new commit on detached is grayed out, git switch -c rescue makes it re-protected by sticky notes.
Narrator: If you want to keep the commits made here, use git switch minus c to create a branch.
Module 7 · Remote repository: clone, fetch, pull, push
- Explain remote (remote) and remote-tracking branches (
refs/remotes/origin/*), the relationship between local branches and upstream, understandahead N, behind M。 - distinguish
git fetch(only updates remote-tracking branches) withgit pull(fetch + merge/rebase/fast forward), understand why it is recommendedpull.ff=onlyOr fetch first and then decide. - Will use
git push -uBuild upstream and understand! [rejected] … (fetch first)/non-fast-forwardand handle it correctly; understand--force-with-lease。
What: Several remotely related names
| name | what is | storage location | who will move it |
|---|---|---|---|
origin | Alias of remote repository (URL + fetch refspec) | .git/config of [remote "origin"] | git remote command |
origin/main | Remote tracking branch: the location of main the last time it communicated with the remote (read-only snapshot) | refs/remotes/origin/main | Only when fetch / pull / push is successful |
main | your local branch | refs/heads/main | your commit/reset/merge |
| upstream | The "default corresponding" remote-tracking branch of the local branch | [branch "main"] remote = origin, merge = refs/heads/main | push -u、branch -u、clone |
Key insights:git status"Your branch is up to date with 'origin/main'" in just take main withlocally recordedorigin/main comparison,Not connected to the Internet. There is a new commit on the remote end but you don't fetch it, it will still say up to date.
Why: Why should it be divided into two steps: fetch and integration?
- fetch issafeof: only download objects, move
origin/*, never modify your branches, indexes, and workspaces. you can firstgit log main..origin/mainSee what others have changed, and then decide how to integrate it. - pull combines two steps into one, which is convenient but automatically integrated: by default, fast forward is enabled; when forking, the new version of Git is not configured
pull.rebase/pull.ffIn the case ofrejectand asks you to choose a strategy (merge, rebase, or fast-forward only).
How: Protocols and Data Flow
- clone =
init+remote add origin URL+fetch(Download all objects and generaterefs/remotes/origin/*) + Create a local branch for the remote default branch and set up upstream + checkout. - fetch: Negotiate with the remote end (Git protocol v2:
ls-refsList citations →fetchSend want/have in the command → the server packs your missing objects into packfile and sends → press refspec locally+refs/heads/*:refs/remotes/origin/*Update the remote-tracking branch and writeFETCH_HEAD。 - pull= fetch + use upstream to integrate the current branch (
--ff-only/--rebase/--no-rebaseThat is, merge). - push: Package the missing objects in the local branch and send them to the remote end, and request the remote end to update the ref. By default, the remote end only acceptsfast forward(The new value must have the old value as its ancestor); otherwise, reject and prompt
fetch first(The remote end has objects that you don’t have locally) ornon-fast-forward(You know the remote commit locally, but your branch doesn't contain it). The hosting platform also enforces branch protection and push rules at this step (Lessons 3 and 4).
URL and authentication (just click here, detailed explanation in Lessons 3 and 4)
| form | Example | Certification |
|---|---|---|
| HTTPS | https://github.com/org/myapp.git | Git Credential Manager (comes with Windows; currently v3.0.2), PAT, OAuth |
| SSH | git@github.com:org/myapp.git | SSH key (ed25519 recommended) |
| local path / file:// | ~/git-lab/remote/myapp.git | File system permissions (used in this lesson) |
When: daily rhythm
- Before starting work:
git fetch→git status -sblook ahead/behind → without local commitgit pull --ff-only。 - Push a new branch:
git push -u origin branch(or configurepush.autoSetupRemote=truedirectly aftergit push)。 - Rejected: fetch first, check the fork situation, then choose rebase (lesson 2) or merge, and finally push. The only thing that has been rewritten isownUsed only when branching
--force-with-lease。
Comparison with similar technologies
| Git | SVN | |
|---|---|---|
| Get updates | fetch(Security) + Integration | svn updateModify working copy directly |
| Post changes | push(Must include the latest remote commit first) | svn commit(File level conflict checking) |
| multiple remotes | Support (origin, upstream, mirror...) | single server |
--force-with-lease, do not force push on the shared branch.Architecture diagram: local, origin and teammates
Flow chart: processing when push is rejected
Three-party synchronization simulator: you ↔ origin ↔ teammates
Click in any order. Below each repository the commits pointed to by its main (and your origin/main) are shown; the terminal shows the actual command output. Try: let your teammates push it first, and then push it directly on your side to see why it was rejected.
Core commands and parameters
| command | function | Key parameters/description |
|---|---|---|
git clone URL [directory] | Copy repository | -b branch、--depth、--filter=blob:none、--bare、--mirror |
git remote | Manage remotely | -v、add、rename、remove、set-url、show origin、prune |
git fetch | Download objects and update remote-tracking branches | --all、--prune、--tags、origin main |
git pull | fetch + integration | --ff-only、--rebase、--no-rebase;Configurationpull.ff/pull.rebase |
git push | Post a local commit | -u、--tags、--follow-tags、--delete、--force-with-lease、--dry-run |
git branch -u origin/x | Set upstream | --unset-upstream;@{u}Refers to upstream |
git ls-remote origin | Do not download the object, directly list the remote references | Troubleshooting "What's on the remote end?" |
cd ~/git-lab/myapp git remote -v git status -sb # Not connected to the Internet: still displayed consistent with origin/main git fetch git status -sb git log --oneline main..origin/main
origin /home/azureuser/git-lab/remote/myapp.git (fetch) origin /home/azureuser/git-lab/remote/myapp.git (push) ## main...origin/main From /home/azureuser/git-lab/remote/myapp f4ac97b..db1616e main -> origin/main ## main...origin/main [behind 1] db1616e docs: add local run instructions
How to read:f4ac97b..db1616e main -> origin/main: The remote main advances from f4ac97b to db1616e, and the local origin/main is updated accordingly. Your main is not moved, so it shows[behind 1]。main..origin/main= Commits that the remote end has but you don’t.
git pull --ff-only git log --oneline -2
Updating f4ac97b..db1616e Fast-forward README.md | 2 ++ 1 file changed, 2 insertions(+) db1616e (HEAD -> main, origin/main, origin/HEAD) docs: add local run instructions f4ac97b (tag: v1.1.0) Merge branch 'hotfix/redis-timeout'
Fast forward: The main pointer moves directly to db1616e, and no new commits are generated.origin/HEADRepresents the remote default branch (newer Git will automatically create/follow it when fetching, byremote.origin.followRemoteHEADControl; 2.56 added global defaultfetch.followRemoteHEAD)。
push rejected (real output)
# A teammate pushed another commit, and you also committed it locally. ( cd ~/git-lab/teammate && git pull -q --ff-only && echo "flask" > x.txt && git add x.txt && git commit -qm "chore: teammate change" && git push -q ) echo "1.2.0" > VERSION && git add VERSION && git commit -qm "chore: add VERSION file" git push
To /home/azureuser/git-lab/remote/myapp.git ! [rejected] main -> main (fetch first) error: failed to push some refs to '/home/azureuser/git-lab/remote/myapp.git' hint: Updates were rejected because the remote contains work that you do not hint: have locally. This is usually caused by another repository pushing to hint: the same ref. If you want to integrate the remote changes, use hint: 'git pull' before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details.
git pull # Configured pull.ff=only by module 0
fatal: Not possible to fast-forward, aborting.
If not configured anypull.rebase/pull.ff(fresh install on Linux), when forkinggit pullThe output is:
hint: You have divergent branches and need to specify how to reconcile them. hint: You can do so by running one of the following commands sometime before hint: your next pull: hint: hint: git config pull.rebase false # merge hint: git config pull.rebase true # rebase hint: git config pull.ff only # fast-forward only hint: hint: You can replace "git config" with "git config --global" to set a default hint: preference for all repositories. You can also pass --rebase, --no-rebase, hint: or --ff-only on the command line to override the configured default per hint: invocation. fatal: Need to specify how to reconcile divergent branches.
The second paragraph prompts only if there is nopull.rebase/pull.ffOccurs during configuration (Git for Windows is usually written at the system level when installingpull.rebase=false, so it will be merged directly on Windows). Recommendations for this course:git pull --rebasePut your local commits after the remote commits (linear history, explained in detail in Lesson 2), thengit push。
git pull --rebase git push git log --oneline --graph -3
Push the new branch and build upstream
git switch -c lab/remote git commit --allow-empty -m "chore: test push" git push -u origin lab/remote git branch -vv | grep lab/remote
To /home/azureuser/git-lab/remote/myapp.git * [new branch] lab/remote -> lab/remote branch 'lab/remote' set up to track 'origin/lab/remote'. * lab/remote 7c1d2e3 [origin/lab/remote] chore: test push
Common mistakes:Not added-uNot open eitherpush.autoSetupRemotetime, next timegit pushReportfatal: The current branch lab/remote has no upstream branch.。Production use:git push --force-with-leaseOnly when the remote branch is still the value of your last fetch will it be overwritten to prevent accidentally deleting the commit just pushed by your teammates.
git switch main # Demonstration ends, return to main
Experiment 7: A complete synchronization and pre-conflict integration (~7 minutes)
behind 1):bash ~/bootstrap-git-lab.sh --force。cd ~/git-lab git clone remote/myapp.git clone2 cd clone2 git branch -a git config --get-regexp '^(remote|branch)\.'
Cloning into 'clone2'... done. * main remotes/origin/HEAD -> origin/main remotes/origin/feature/login remotes/origin/main remote.origin.url /home/azureuser/git-lab/remote/myapp.git remote.origin.fetch +refs/heads/*:refs/remotes/origin/* branch.main.remote origin branch.main.merge refs/heads/main
Only local main is created;feature/loginJust remotely track the branch.git switch feature/loginA local branch with the same name is automatically created and tracked by origin (DWIM behavior).
cd ~/git-lab/myapp git fetch git status -sb # [behind 1] git log --oneline -p main..origin/main | head -15 git pull --ff-only
! [rejected] main -> main (fetch first)。git fetch git status -sb # ## main...origin/main [ahead 1, behind 1] git pull --rebase git push git status -sb # ## main...origin/main
git ls-remote origin refs/heads/main git rev-parse main # Both are consistent git -C ~/git-lab/teammate pull --ff-only && git -C ~/git-lab/teammate log --oneline -1
rm -rf ~/git-lab/clone2 git switch main; git push origin --delete lab/remote 2>/dev/null; git branch -D lab/remote 2>/dev/null # Want to restore to the initial state: bash ~/bootstrap-git-lab.sh --force
Case 1: Use git pull to deploy the script, and a merge commit appears online
Question:Deployment script on servercd /srv/app && git pull, someone modified the file directly on the server and committed it, and the pull resulted in a merge commit or even a conflict, and the deployment got stuck.Method:Deployments should not be pull on the server; instead CI build artifacts/images (Docker lesson). When deploying with Git:git fetch origin && git reset --hard origin/main(Clearly "subject to the remote end"), and commit on the server is prohibited.Limitations:reset --hard will discard local modifications on the server, which is exactly the purpose, but first make sure there is no configuration that needs to be preserved (the configuration should come from environment variables or key management).
Case 2: Two remotes in the fork workflow
Question:Contribute to open source projects, clone your own fork after forking, and find that your main is lagging behind after the upstream update.Method:git remote add upstream https://github.com/originalproject.git;git fetch upstream;git switch main && git merge --ff-only upstream/main && git push origin main。Limitations:Do not develop directly on the main of the fork. Put the functions in independent branches to facilitate PR (Lesson 3).
Case 3: Forced push overwrites teammate’s commit
Question:After developer rebasegit push --forceGo to the shared release branch and cover the fix pushed by your teammate 10 minutes ago.Method:Teammates retrieve the commit in their local reflog/origin/release old value and push it again; the team stipulates that only--force-with-lease, and disable forced pushing of shared branches on the platform (Lesson 3).Limitations:--force-with-leaseThe protection will be lost when you have just fetched (the remote-tracking branch has been updated); you can use--force-with-lease=branch:expected hashExplicitly specified, or combined with--force-if-includes。
Common errors and solutions
! [rejected] main -> main (non-fast-forward)
Reason:Your branch does not contain the latest commit from the remote branch (someone on the remote branch pushed it, or you amend/rebase rewritten the pushed commit).
git fetch git status -sb git log --oneline --graph --all -10
Fix:Shared branch:git pull --rebaseOr merge and then push; own branch and confirm to overwrite:git push --force-with-lease。
fatal: The current branch lab/remote has no upstream branch.
Reason:There is no upstream when a new branch is pushed for the first time.
Fix:git push -u origin lab/remote;or one-time configurationgit config --global push.autoSetupRemote true。
fatal: 'origin' does not appear to be a git repository / Could not read from remote repository.
Reason:No remote named origin, bad URL, or authentication failed (SSH keys/permissions).
git remote -v git ls-remote origin ssh -T git@github.com # Test authentication during SSH
Fix:git remote add origin URLorgit remote set-url origin URL; See Lessons 3 and 4 for authentication issues.
There is no tracking information for the current branch. Please specify which branch you want to merge with.
Reason:git pullDon't know which remote branch to integrate from.
Fix:git branch --set-upstream-to=origin/main, orgit pull origin main。
error: src refspec main does not match any
Reason:There is no branch named main locally (it has not been committed yet, or the branch is called master).
git branch git log --oneline -1
Fix:Commit first; or push the correct branch name; orgit branch -m master main。
1. Without modifying any local branches, check which commits the remote main has more than you.
git fetch origin git log --oneline HEAD..origin/main
2. Delete the remote branch lab/remote and clean up the local expired remote-tracking branches.
git push origin --delete lab/remote git fetch --prune
Start work in the morning,git status"Your branch is up to date with 'origin/main'" is displayed, you develop and commit directly, and the push is rejected in the afternoon. Why didn't status remind you in the morning? How to avoid it in the future?
status only compares the local main and the locally cached origin/main, not connected to the Internet; there are new commits on the remote end in the morning but you do not fetch, so the cache is old. Avoid: Before starting workgit fetch(orgit pull --ff-only) look againgit status -sb;Fetch again before push; used when rejectedgit pull --rebaseIntegrate and then push, rather than push.
Verified instructional videos
Official documentation
- Pro Git 2.5 Working with Remotes
- Pro Git 3.5 Remote Branches
- git-push: Note about fast-forwards · git-pull · gitprotocol-v2
Video storyboard (approximately 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Picture: There are two post-it notes on your notebook, main and origin/main. Origin/main is a semi-transparent "photo".
Narrator: origin/main is the picture of the remote branch, which is only updated during fetch, pull, and push. status is not connected to the Internet.
Screen: Teammates push, remote progress; you fetch, the photo is updated, the main does not move, and behind 1 is displayed.
Narrator: fetch only downloads and updates photos, which is very safe. pull equals fetch plus integration.
Screen: When you push, the server checks whether the new value contains the old value. If not, it stamps a red rejected value.
Narrator: push only accepts fast forward. If the remote end has a commit that you don't have, it will be rejected.
Screen: pull --rebase Move your commit after your teammates commit it, and push again successfully.
Narrator: Integrate first, then push. Only consider force with lease on your own branch.
Module 8 · Getting Started with Configuration, .gitignore, and Troubleshooting
- To master the three (actually four) levels of configuration system / global / local / worktree and priority, use
git config --show-origin --show-scopeFind out where a value comes from; configure common aliases and conditional includes (includeIf)。 - write the correct
.gitignore(wildcard, directory, anchor, negation,**), knowing that "tracked files are not affected by .gitignore", and usinggit check-ignore -vDebugging rules; understanding.git/info/excludeFiles are ignored globally. - understand
.gitattributesThe purpose of (end of linetext/eol, binary, diff driver, LFS), and withcore.autocrlfrelationship. - The most common entry-level errors can be handled according to the interactive troubleshooting tree: not a git repository, detached HEAD, rejected push, merge not completed, identity not configured, etc.
What: Configuration level and priority
| level | File | Command parameters | Scope |
|---|---|---|---|
| system | /etc/gitconfig(Git for Windows:C:/Program Files/Git/etc/gitconfig) | --system | All users of this machine |
| global | ~/.gitconfigor~/.config/git/config | --global | All repositories of the current user |
| local | .git/config | --local(default) | Current repository |
| worktree | .git/config.worktree | --worktree | Current working tree (requiresextensions.worktreeConfig) |
| Command line/environment | git -c key=value、GIT_CONFIG_* | — | single command |
Git reads system → global → local → worktree → command line in sequence,What is read later overwrites what is read first(Multi-valued keys such asremote.origin.fetchIt is cumulative). So "I clearly set it in global, why doesn't it take effect" is usually local or-ccovered it.
Common configurations and aliases
[user]
name = Your Name
email = you@example.com
[init]
defaultBranch = main
[core]
editor = code --wait
autocrlf = input # Use true on Windows
[pull]
ff = only
[push]
autoSetupRemote = true
[fetch]
prune = true
[alias]
st=status-sb
lg = log --oneline --graph --decorate --all
last = log -1 --stat
unstage = restore --staged
amend = commit --amend --no-edit
whoami = !git var GIT_AUTHOR_IDENT
[includeIf "gitdir:~/work/"]
path = ~/.gitconfig-work # The company repository automatically uses the company email
to!The aliases that begin with are executed as shell commands.includeIf "gitdir:…"Letting repositories in different directories use different identities is a standard practice to prevent "commit using the wrong email address" when maintaining both personal and company projects; starting from 2.56includeIfYou can also match by working tree location (new feature, please refer to the official documentation).
What: .gitignore rules
| mode | meaning | Example |
|---|---|---|
*.log | Matching file names in any directory | debug.log、logs/app.log |
build/ | tail/: Matches only directories | Any level of build directory |
/TODO | Beginning/: Anchor to the directory where .gitignore is located | Only ignore TODOs in the root directory |
doc/*.txt | Contains in the middle/: Anched relative to the directory where .gitignore is located,*Do not cross directories | doc/a.txt, does not matchdoc/x/b.txt |
**/temp、a/**/b、logs/** | **Match any directory level | a/b、a/x/y/b |
!keep.log | negation: re-inclusion | *.log was ignored previously, but keep.log was retained |
\#file、\!file | Escape the leading # or ! | — |
- Later rules in the same file take precedence; .gitignore in deeper directories takes precedence over those above.
- After the parent directory is ignored, it cannot be used.
!Re-include files within(Git will not step into ignored directories for performance reasons). to be written aslogs/*+!logs/.gitkeep, instead oflogs/+!logs/.gitkeep。 - .gitignore only affects untracked files. Documents that have already been committed must be
git rm --cachedStop tracking. - Three sources: in the repository
.gitignore(commit, shared by team),.git/info/exclude(Only for this repository, not committed),core.excludesFile(Default~/.config/git/ignore, put.DS_Store、.idea/etc. personal editor files).
What: Introduction to .gitattributes
| Properties | Purpose | Example |
|---|---|---|
text=auto / text / -text | Whether to normalize line endings according to text (LF is stored in the repository) | * text=auto |
eol=lf|crlf | Line endings to enforce when checking out | *.sh text eol=lf、*.bat text eol=crlf |
binary | = -diff -merge -text | *.png binary |
diff=… / merge=… | Custom diff/merge driver | *.lock merge=ours(Requires driver configuration) |
filter=lfs | Git LFS (Lesson 6) | *.zip filter=lfs diff=lfs merge=lfs -text |
export-ignore | git archiveexclude when | tests/ export-ignore |
End of line strategy:.gitattributesCommitted with the repository, it takes effect for everyone and takes precedence over everyone's owncore.autocrlf; Therefore team projects should be written in the repository.gitattributes(myapp already does this), rather than relying on everyone's native configuration. After the Shell script is converted to CRLF on Windows, it will report when running in the Linux container/bin/bash^M: bad interpreter——*.sh text eol=lfExactly for this.
Why / When
- Configuration: Unify team behavior (pull policy, line endings, hook paths) and reduce "no problem on my machine".
- Ignore: Prevent build artifacts, dependency directories, local keys (
.env) Get into the repository - Secret leaks often start with a poorly written ignore rule. - Troubleshooting: 80% of the errors reported in the entry-level stage come from more than a dozen fixed situations. Mastering the troubleshooting path is more important than remembering each error report.
Comparison with similar technologies
| .gitignore | .dockerignore (Docker class) | .gitattributes | |
|---|---|---|---|
| function | Which untracked files don't go into Git | Which files do not enter the build context | How files are processed (line endings, diff, LFS) |
| Grammar | gitignore mode | Similar but based on Go filepath.Match, details are different | schema + properties |
git rm --cached; and it still exists in history. ② "logs/then!logs/keep"Just keep" - the parent directory cannot be re-included after being ignored. ③ "core.autocrlf is a team setting" - it is a personal setting, and the team should use .gitattributes. ④ "After changing git config user.email, old commits will also change" - the identity is written in the commit object, which only affects subsequent commits.Configuration overlay: same key, who has the final say
Decision diagram: why a file was (or was not) ignored
Interactive: .gitignore rule tester
Write the rules on the left (one per line, the syntax is the same as .gitignore, located in the root directory of the repository), and the path on the right (directory starting with/end). Click "Test" to see whether each path is ignored and which line is hit - output format imitationgit check-ignore -v --no-index. Realized*、?、**, tail/, anchor,!Negation, and the rule "parent directories are ignored and cannot be re-included"; character classes[abc]If the rare syntax is not implemented, the real Git shall prevail.
Core commands and parameters
| command | function | Key parameters/description |
|---|---|---|
git config | Read and write configuration | --global/--local/--system、--list --show-origin --show-scope、--get、--unset、--edit; New style subcommandgit config get/set/list/unset(2.46+) |
git var | View derived identities, editors, and more | GIT_AUTHOR_IDENT、GIT_EDITOR、-l |
git check-ignore | Debug ignore rules | -v(Show source and line number),--no-index(check rules even if tracked),--stdin |
git status --ignored | Show ignored files | -swhen displayed as!! |
git rm --cached | Stop tracing but keep local files | -rDirectory |
git check-attr | View the file's effective attributes | -a file |
git add --renormalize . | Renormalize line endings by new .gitattributes | Execute once after modifying the end-of-line policy |
cd ~/git-lab/myapp git config --list --show-origin --show-scope | grep -E "user\.|autocrlf|pull\." git config --global alias.lg "log --oneline --graph --decorate --all" git config --global alias.st "status -sb" git lg | head -3; git st
system file:C:/Program Files/Git/etc/gitconfig core.autocrlf=true system file:C:/Program Files/Git/etc/gitconfig pull.rebase=false global file:C:/Users/you/.gitconfig user.name=Your Name global file:C:/Users/you/.gitconfig user.email=you@example.com global file:C:/Users/you/.gitconfig core.autocrlf=true global file:C:/Users/you/.gitconfig pull.ff=only
How to read:When the same key appears multiple times,last lineis the effective value; usegit config --show-origin --get core.autocrlfJust look at the one that works.
mkdir -p __pycache__ && touch __pycache__/app.cpython-313.pyc .env debug.log git check-ignore -v __pycache__/app.cpython-313.pyc .env debug.log app.py; echo "Exit code=$?" git status --ignored -s
.gitignore:1:__pycache__/ __pycache__/app.cpython-313.pyc .gitignore:4:.env .env .gitignore:5:*.log debug.log Exit code=0 !! .env !! __pycache__/ !!debug.log
Format:Source file: Line number: Rule <TAB> path。app.pyNot ignored so no output; as long as one path is ignored, the exit code is 0 (all not ignored are 1).Common mistakes:check-ignore default pairTrackedThe file does not report rules, you need to add--no-index。
# Stop tracking a committed file (take settings.env as an example) echo "settings.env" >> .gitignore git rm --cached settings.env git status -s git commit -m "chore: stop tracking settings.env"
rm 'settings.env' M .gitignore D settings.env
The file is still on disk, but is no longer tracked from the next commit; older versions in history still exist (including the old FAKE_SECRET).
printf '#!/bin/sh\necho hi\n' > deploy.sh && git add deploy.sh git check-attr -a app.py deploy.sh git ls-files --eol app.py deploy.sh
app.py: text: auto deploy.sh: text: set deploy.sh: eol: lf i/lf w/crlf attr/text=auto app.py i/lf w/lf attr/text eol=lf deploy.sh
git ls-files --eolDisplay the line endings and effective attributes of the index (i/) and workspace (w/): app.py is LF in the repository and CRLF in the Windows workspace; deploy.sh is LF on both sides.Production use:Script reports in container images^MWhen an error occurs, use this command to locate it at a glance.
Lab 8: Aliases, Conditional Identity, and Ignore Rule Debugging (~6 minutes)
git config --global alias.lg "log --oneline --graph --decorate --all" git config --global alias.unstage "restore --staged" git config --global alias.whoami '!git var GIT_AUTHOR_IDENT' cd ~/git-lab/myapp && git lg | head -5 && git whoami
mkdir -p ~/work
cat > ~/.gitconfig-work <<'EOF'
[user]
email = you@company.example
EOF
git config --global includeIf."gitdir:~/work/".path "~/.gitconfig-work"
git init -q ~/work/demo && git -C ~/work/demo config user.email
git -C ~/git-lab/myapp config user.email
you@company.example you@example.com
gitdir:Mode starts with/The end means "all repositories in this directory". Cleanup after verification:rm -rf ~/work/demo, and usegit config --global --unset includeIf.gitdir:~/work/.pathDelete (or keep for later use).
cd ~/git-lab/myapp && git switch -c lab/ignore mkdir -p logs && touch logs/.gitkeep logs/app.log printf 'logs/\n!logs/.gitkeep\n' >> .gitignore git status -s # Can't see logs/.gitkeep git check-ignore -v logs/.gitkeep
.gitignore:6:logs/ logs/.gitkeep
The hit is line 6logs/: The directory itself is ignored, Git will not enter the directory,!logs/.gitkeepNever had a chance to take effect.
sed -i 's#^logs/$#logs/*#' .gitignore git check-ignore -v logs/.gitkeep logs/app.log; git status -s
.gitignore:7:!logs/.gitkeep logs/.gitkeep .gitignore:6:logs/* logs/app.log M .gitignore ?? logs/
The output for .gitkeep is the negative rule (starting with!Beginning means "not ignored");?? logs/Only .gitkeep will be added.
echo ".vscode/" >> .git/info/exclude # Only for this repository, not committed mkdir -p ~/.config/git && echo ".DS_Store" >> ~/.config/git/ignore # For all repositories mkdir -p .vscode && touch .vscode/settings.json git check-ignore -v .vscode/settings.json
.git/info/exclude:7:.vscode/ .vscode/settings.json
The line number depends on the number of comment lines already in the exclude file (the default template has 6 comment lines).
git restore .gitignore; rm -rf logs .vscode __pycache__ .env debug.log git switch main && git branch -D lab/ignore
Case 1: Committed company code using private email
Question:The developer's global configuration is a private mailbox, and commits to the company's repository are displayed as private identities. The platform cannot associate the account, and the compliance audit does not pass.Method:use includeIf "gitdir:~/work/"Automatic switching; turn on the push rule "Submission email must be a verified email" on the platform side (GitLab push rules, GitHub email privacy settings, lessons 3 and 4).Limitations:Author information for pushed commits can only be corrected by rewriting history, which is usually not worth it - just fix it from now on.
Case 2: node_modules is committed and the repository expands to 800 MB
Question:I forgot to write .gitignore for the new project, and the dependency directory was included in the first commit.Method:addnode_modules/to .gitignore,git rm -r --cached node_modulesand commit; when the repository has been pushed and the volume is a problem, usegit filter-repo --path node_modules --invert-pathsCleaning up history (Lesson 7).Configuration:Use the github/gitignore template when creating a new repository; add large file checking in pre-commit (Lesson 5).Limitations:Rewriting history requires all members to re-clone.
Case 3: The script committed by Windows developers cannot be executed in the container
Question:Docker image inentrypoint.shnewspaperexec /entrypoint.sh: no such file or directory(actually CRLF causes the interpreter name to become/bin/sh\r)。Method:repository plus*.sh text eol=lf, executegit add --renormalize .and commit; usegit ls-files --eolVerify.Limitations:The image that has been built needs to be rebuilt; the developer's local old workspace needs to be checked out again (git rm --cached -r . && git reset --hard, first confirm that there are no uncommitted modifications).
Interactive troubleshooting tree: common errors when getting started with Git
Select the error or phenomenon you see and follow the prompts to locate it step by step. Each conclusion gives diagnostic commands and repair methods, and marks the module or subsequent course where the detailed explanation is located.
Common Errors Quick Check
fatal: not a git repository (or any of the parent directories): .git
Reason:None in the current directory or any parent directories.git;or the path is wrong in Git Bash; orGIT_DIRSetting error.
pwd; ls -a git rev-parse --show-toplevel
Fix:cd ~/git-lab/myapp;New projectgit init; If the owners of the mounting directories in the container are different, the next "dubious ownership" may be triggered.
fatal: detected dubious ownership in repository at '/srv/app'
Reason:Since 2.35.2, Git refuses operations when the owner of the repository directory is different from the current user (defending CVE-2022-24765). Commonly used in Docker mounted volumes, CI, and sudo.
Fix:After confirming that the directory is trustworthygit config --global --add safe.directory /srv/app; Or modify the directory owner. Don't set it randomlysafe.directory=*。
Author identity unknown *** Please tell me who you are.
Author identity unknown *** Please tell me who you are. Run git config --global user.email "you@example.com" git config --global user.name "Your Name" to set your account's default identity. Omit --global to set the identity only in this repository. fatal: unable to auto-detect email address (got 'azureuser@vm-lab.(none)')
Fix:Follow the prompts to set; used in CIgit config user.name/email(local) or environment variablesGIT_AUTHOR_NAMEWait.
/bin/bash^M: bad interpreter: No such file or directory
Reason:Script checked out as CRLF.
git ls-files --eol deploy.sh file deploy.sh
Fix:.gitattributesadd*.sh text eol=lf,git add --renormalize ., check out again.
1. Find outcore.autocrlfWhich file does the effective value come from.
git config --show-origin --show-scope --get core.autocrlf
2. Ignore all files in the logs directory, but keep logs/.gitkeep and verify.
printf 'logs/*\n!logs/.gitkeep\n' >> .gitignore git check-ignore -v logs/.gitkeep logs/x.log
you put.envAdded .gitignore, butgit statusStill showingM .env, and a colleague said he can see your database password in the repository. What's the reason? What are the complete disposal steps?
.env is already tracked, .gitignore has no effect on tracked files, and it still exists in history. Disposal: ① Immediately rotate (invalidate) leaked passwords - this is the first priority; ②git rm --cached .envAnd commit, make sure there is .gitignore.env; ③ usegit log -S password fragment --allAssess the scope of impact; ④ Use git filter-repo to clear the history and coordinate all staff to re-clone according to Lesson 7; ⑤ Enable confidential scanning and push protection on the platform (Lesson 3). Simply deleting the file won't solve the problem.
Verified instructional videos
Official documentation
- git-config (including includeIf, FILES)
- gitignore(5) · git-check-ignore
- gitattributes(5)
- Pro Git 8.1 Git Configuration
- github/gitignore template collection
Video storyboard (approximately 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: Four layers of transparency film, system, global, local, and command line, are stacked together, with the values on the top layer showing through.
Narrator: Git configures hierarchical reading, so that what is read later overwrites what is read first. Use show-origin to find the origin of each value.
Picture: .gitignore rules are highlighted line by line, the logs directory is covered in gray, and .gitkeep inside cannot "escape".
Narrator: The parent directory is ignored and the files within it cannot be re-included. To be written as logs slash asterisk, and then use exclamation point to retain gitkeep.
Image: Committed .env file passes through .gitignore's net, red warning.
Aside: .gitignore only ignores untracked files. For those that have been committed, use git rm to reduce cached to stop tracking, and the leaked keys must be rotated.
Picture: The troubleshooting tree branches out from "see what errors are reported" into branches such as not a git repository, rejected, and detached.
Narrator: Don’t panic when you encounter an error. Look at the first line of keywords first, and then follow the troubleshooting tree to locate it step by step.
Command cheat sheet
Installation and configuration
sudo add-apt-repository -y ppa:git-core/ppa && sudo apt install -y git git --version git config --global user.name "Your Name" git config --global user.email "you@example.com" git config --global init.defaultBranch main git config --global core.editor "code --wait" git config --global pull.ff only git config --global push.autoSetupRemote true git config --list --show-origin --show-scope
Objects and low-level commands
git cat-file -t OBJ # type
git cat-file -p OBJ # content
git cat-file -s OBJ # size
git hash-object -w FILE # Write blob
git ls-tree -r REV # List tree
git ls-files -s # View index
git write-tree # index → tree
git commit-tree T -p P -m M # tree → commit
git update-ref refs/heads/X C
git rev-parse REV / REV:path / REV^{tree}
git count-objects -vH; git gcthree areas
git status -sb git add -p FILE # Block staging git add -N FILE # intent-to-add git diff # workspace vs index git diff --staged # index vs HEAD git diff HEAD # workspace vs HEAD git restore --staged FILE # Cancel staging git rm --cached FILE # Stop tracking
Commits and History
git commit -m "feat(scope): subject" -m "why..." git commit -v # Display diff in editor git log --oneline --graph --decorate --all git log --oneline A..B git log --first-parent --oneline main git show REV / git show REV:path git blame -L 6,6 FILE / -L :func FILE git log -S "string" --all git log -G "regex" -p --PATH git log -L :func:FILE
Cancel
git restore FILE # Discard workspace modifications ⚠ git restore --source=REV -SW FILE # Retrieve the old version git reset --soft HEAD~1 # Undo the commit and keep the temporary cache git reset HEAD~1 # Undo commit and temporary save git reset --hard HEAD~1 # Discard all ⚠ git reset --hard ORIG_HEAD # regret medicine git revert REV/revert -m 1 MERGE git commit --amend [--no-edit] # Only not pushed git reflog -10 git clean -n → git clean -fd
Branches and HEAD
git branch -vv git switch -c NEW [START] git switch - # Previous branch git switch --detach v1.0.0 git branch -m OLD NEW git branch -d NAME / -D NAME git branch --merged main git symbolic-ref HEAD git branch --show-current
remote
git clone URL [DIR] git remote -v /add/set-url/show origin git fetch [--prune] git status -sb # ahead/behind (based on the last fetch) git log --oneline HEAD..origin/main git pull --ff-only / --rebase git push -u origin BRANCH git push --force-with-lease # Only used for own branches git push origin --delete BRANCH git ls-remote origin
Ignore and attribute
__pycache__/ *.pyc .env logs/* !logs/.gitkeep /build # .gitattributes * text=auto *.sh text eol=lf *.png binary # debug git check-ignore -v PATH git status --ignored -s git ls-files --eol
Quick troubleshooting table
| Error report/phenomenon | First diagnostic command | Common fixes | module |
|---|---|---|---|
not a git repository | pwd; git rev-parse --show-toplevel | cd to repository /git init | M8 |
Author identity unknown | git var GIT_AUTHOR_IDENT | Set user.name / user.email | M0 |
HEAD detached at … | git status、git reflog | git switch -c NEWorgit switch main | M6 |
! [rejected] … (fetch first) | git fetch; git status -sb | git pull --rebaseAfter push | M7 |
Not possible to fast-forward / divergent branches | git log --oneline --graph --all -10 | Choose rebase or merge (Lesson 2) | M7 |
has no upstream branch | git branch -vv | git push -u origin BRANCH | M7 |
would be overwritten by checkout | git status -s | Switch after commit / stash | M5 |
index.lock: File exists | ps aux | grep git | Delete the lock after confirming that there is no process | M3 |
| Commit "disappears" | git reflog | git branch rescue HASH | M5/M6 |
| .gitignore does not take effect | git ls-files FILE; git check-ignore -v FILE | git rm --cached/amend rules | M8 |
dubious ownership | ls -ld . | safe.directoryor modify the owner | M8 |
Recommended configuration snippet (~/.gitconfig)
[user]
name = Your Name
email = you@example.com
[init]
defaultBranch = main
[pull]
ff = only
[push]
autoSetupRemote = true
[fetch]
prune = true
[rerere]
enabled = true # Lesson 2: Remember conflict resolution
[alias]
st=status-sb
lg = log --oneline --graph --decorate --all
unstage = restore --staged
last = log -1 --stat
[includeIf "gitdir:~/work/"]
path = ~/.gitconfig-work
Comprehensive experiment + final exam
/healthzIncrease the version number, add a VERSION file, make a mistake in the process and undo it, and finally push it to origin and let "teammates" get your commit. Use plumbing commands every step of the way to prove that you know what's going on inside Git.bash ~/bootstrap-git-lab.sh --force cd ~/git-lab/myapp git fetch && git status -sb # [behind 1] git pull --ff-only git log --oneline -1 # db1616e docs: add local run instructions git switch -c release/1.2.0
sed -i 's/"status": "ok"/"status": "ok", "version": "1.2.0"/; s/Hello from myapp!/Hello from myapp (debug)!/' app.py git add -p app.py # s → n (skip debug greeting) → y (temporary healthz) git diff --staged # should only see version git commit -m "feat(api): expose version in /healthz" git restore app.py # Discard debug modifications git status -s # clean
git cat-file -t HEAD git cat-file -p HEAD # tree, parent=db1616e..., your identity git ls-tree HEAD app.py # new blob of app.py git cat-file -p HEAD:app.py | tail -3 git diff --stat HEAD~1 HEAD git rev-parse HEAD:README.md HEAD~1:README.md # Same: unmodified file reuse blob
echo "1.2.O" > VERSION # Letter O, error git add VERSION && git commit -m "chore: add VERSOIN" echo "1.2.0" > VERSION echo "## 1.2.0 - healthz reports version" > CHANGELOG.md git add VERSION CHANGELOG.md git commit --amend -m "chore: add VERSION and CHANGELOG" # It has not been pushed yet, you can amend git reflog -3 # You can see the commit before amend git show --stat HEAD
git reset --soft HEAD~1 && git status -s # A CHANGELOG.md / A VERSION
git reset HEAD && git status -s # ?? CHANGELOG.md / ?? VERSION
git reflog -3 # HEAD@{2} = commit (amend): chore: add VERSION and CHANGELOG
git reset --hard HEAD@{2}
git log --oneline -3 # Commit is back
git status -s # clean
Why not useORIG_HEAD? second timegit reset HEADORIG_HEAD will also be updated (at this point it points to the healthz commit after the soft reset), soreset --hard ORIG_HEADCan only go back to healthz commit. The reflog records every move and is a reliable backup - this is what Lesson 7 will go into.
echo "*.local" >> .gitignore && touch secrets.local git check-ignore -v secrets.local git add .gitignore && git commit -m "chore: ignore *.local files" git config --show-origin --get user.email
git switch main git merge --ff-only release/1.2.0 # main fast forward to the release branch (see Lesson 2 for details on merging) git tag -a v1.2.0 -m "release 1.2.0" git push origin main --follow-tags git cat-file -t v1.2.0 # tag git ls-remote origin refs/tags/v1.2.0 refs/heads/main cd ~/git-lab/teammate && git pull --ff-only && git log --oneline --decorate -4
cd ~/git-lab/myapp git revert --no-edit HEAD # Undo "ignore *.local" (pushed) git push git log --oneline -3
Open-ended self-assessment (answer yourself first, then expand for reference answers)
1.Describe it in four sentencesgit add VERSION && git commitWhat is written and changed in .git.
add: Calculate SHA-1 of "blob length\0 content", write the blob into objects, and register VERSION → blob in the index. Commit: Generate tree from index (reuse unchanged subtree and blob), create commit object (tree, parent=HEAD refers to commit, identity, time, information). Finally, update the branch ref pointed by HEAD (such as refs/heads/main) to the new commit and write the reflog. The HEAD file itself is unchanged.
2.Why is it said that Git stores snapshots instead of differences? What is the delta of packfile?
Each commit points to a complete tree, representing the state of the entire project at the time of the commit; the difference is calculated when comparing the two trees. The delta in packfile is the compression optimization of the storage layer, which is transparently restored when reading the object without changing the data model.
3. git diff、git diff --staged、git diff HEADWhat are compared?
Workspace vs Index; Index vs HEAD; Workspace vs HEAD. The most important thing before committing is--staged, which is what will be committed.
4.When to use revert and when can reset / amend be used?
Submissions that have been pushed to a shared branch and that others may work on based on it can be revert (only incremented, not subtracted); commits that only exist locally can be reset / amend. After rewriting the pushed personal branch, you need to--force-with-lease。
5.What is detached HEAD? What are the risks of committing in them and how are they remedied?
HEAD points directly to commits rather than branches. The new commit is not referenced by any branch. It can only be retrieved from the reflog after being cut away. It may be gc after it expires. Remedy:git switch -c new branch(on the spot) orgit branch new branch hash(Get the hash from the reflog afterwards).
6.How does "git status show up to date, but push rejected" happen?
status only compares the local branch with the local remote-tracking branch (the snapshot of the last fetch), which is not connected to the Internet; the remote end has new commits after your last fetch, and your branch does not contain them. The push is not fast forward, so it is rejected. First fetch, then rebase/merge, then push.
Final exam (12 questions, covering all modules)
Sources and imprints
| Topic | Verify conclusion | Source (Accessed on 2026-11-15) |
|---|---|---|
| Git latest version | git-scm.com displays the latest source code version2.56.1(2026-10-26) | git-scm.com |
| Git 2.56.0 new features | git history drop(experimental),git refs create/delete/update/rename、git replay --linearize、git branch --delete-merged、git add --resolved、git statusAdvice when falling behindgit pull <remote> <branch>、fetch.followRemoteHEAD、includeIfMatches working tree positions and most subcommands-hExit code changed to 0 | RelNotes/2.56.0.adoc |
| switch / restore | Introduced in 2.23; 2.51.0 release notes announced no longer marked as experimental; BreakingChanges: checkout replaced by both but all three retained | RelNotes/2.51.0 (native Git documentation) ·BreakingChanges |
| Git 3.0 plan | No release date yet; The new repository defaults to SHA-256 (SHA-1 is not abandoned, and needs to be ecologically ready), default reftable, default branch main, Rust mandatory (automatically detected by 2.52 Meson, enabled by default in 2.55),safe.bareRepositoryDefault explicit; removes grafts,pack-redundant、whatchangedWait. (The schedule for 2.98/2.99 LTS/3.0 in the spring of 2027 mentioned in the course specification comes from the Contributor Summit discussion and has not been confirmed by official documents. This course does not serve as a statement of fact) | git-scm.com/docs/BreakingChanges |
| Ubuntu installation | ppa:git-core/ppa(Ubuntu Git Maintainers, "Git stable releases"); Uploaded on 2026-11-111:2.56.1-0ppa1, including 24.04/22.04/26.04/26.10 builds | Launchpad git-core PPA |
| Git for Windows / GCM | Git for Windows v2.56.1.windows.1(2026-11-10);Git Credential Manager v3.0.2(2026-10-26) | git-for-windows releases · GCM releases |
| Object Model and Hashing | Object ID = SHA-1("Type length\0 content");printf 'hello git\n'blob ID 8d0e412… (SHA-256 repository is 0cee7ef…);--object-format=sha256、--ref-format=reftableAll tested on Git 2.51 | Pro Git 10.2 · hash-function-transition |
| Practice repository output | The bootstrap script actually runs on Git 2.51.2 (Git for Windows); all output marked "Hash should be exactly the same as yours" (commits, trees, blobs, tag hashes, packfile object statistics, log/blame/show output, add -p interaction, rejected push, divergent pull prompts) are real running results | Local actual measurement |
| Conventional Commits | 1.0.0:feat→MINOR、fix→PATCH、!/BREAKING CHANGE→MAJOR; the remaining types are conventions | conventionalcommits.org |
| command semantics | reset / restore / revert / switch / push / pull / gitignore / gitattributes / config behavior | git-scm.com/docs · Pro Git version 2 |
Video verification instructions
The following videos have been verified through the YouTube oEmbed interface (2026-11-15) that the title, channel and video ID are consistent: Fireship "Git Explained in 100 Seconds" (hwP7WQkmECE), "13 Advanced (but useful) Git Techniques and Shortcuts" (ecK3EnyGD8o); Missing Semester "Lecture 6: Version Control (git) (2020)" (2sjqTHE0zok); CS50 "Git Internals by John Britton of GitHub - CS50 Tech Talk" (lG90LZotrpo); GitLab "Git Internals - How Git Works - Fear Not The SHA!" (P6jD966jzlk); HackersOnBoard "[Linux.conf.au 2013] - Git For Ages 4 And Up" (1ffBJ4sVUb4); Corey Schafer "Git Tutorial for Beginners: Command-Line Fundamentals" (HVsySz-h9r4), "Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits" (FdZecVxzJbk), "Git Tutorial: Using the Stash Command" (KLEDKgMmbBI); Programming with Mosh "Git Tutorial for Beginners: Learn Git in 1 Hour" (8JJ101D3knE); freeCodeCamp.org "Git and GitHub for Beginners - Crash Course" (RGOj5yH7evk), "Git for Professionals Tutorial - Tools & Concepts for Mastering Version Control with Git" (Uszj_k0DGsg); ByteByteGo "How Git Works: Explained in 4 Minutes" (e9lnsKot_SQ); codebasics "Git Tutorial 8 - .gitignore file" (ErJyWO8TGoM). oEmbed does not return the duration and release date. The duration in the card is a rough description; some videos were recorded earlier thangit switch/restore, the order shall be subject to this lesson.
Audio explanation
The Speech tab uses the browser's Web Speech API (speechSynthesis, zh-CN) read the explanation text aloud in real time, and English terms are pronounced in en-US. The effect depends on the voice installed in the operating system (Windows "Microsoft Xiaoxiao/Yunxi", macOS "Tingting", etc.). This courseware generation environment cannot call the TTS service, so there is no embedded MP3; when offline audio is needed, the lecture notes can be generated by TTS services such as Azure AI Speech.
Known limitations
- The practice repository is generated by a script with a fixed identity and time. The commit, tree, blob, and tag hashes are the same for everyone; the commit hash, time, and path you create (such as
/home/azureuser), packfile name is an example value. - The output is measured on Git 2.51.2 (Windows). The output copy of Git 2.56 may be slightly different (for example, 2.56's
git statusAdditional suggestions when falling behindgit pull);git add -pThe list of keys available in the interactive prompt changes from version to version. - Some experimental commands (PPA installation, macOS/Windows installation, includeIf, reset --hard, etc.) are not executed one by one in this courseware generation environment. Please check your results according to "Expected Output".
- on Windows
sed -iAvailable in Git Bash; macOS comes with BSD sed which needs to be written assed -i ''(or install GNU sed). - The state changes in the animation and simulator are schematic and used to illustrate the mechanism; the output of the "git log parameter combiner" is obtained by running it in advance in the real repository. The .gitignore tester does not implement uncommon syntax such as character classes.
- All content related to Git 3.0 is "planned", and the latest version at git-scm.com/docs/BreakingChanges shall prevail.