3.1 Creating Your First Git Repository
Prerequisites: Chapter 2 (Terminal and Shell)
Estimated time: 12 minutes
Exercise environment: Bash and Git 2.28 or higher versions; all configurations are written only to the temporary repository
You are ready to continue when: you can create a temporary repository and explain the workspace, staging area, and HEAD
Git does not record every keystroke or decide what is worth saving. It stores only project states that you explicitly stage and commit. That is the first distinction between version control and automatic backup.
Setting Up an Isolated Repository
git --version
workdir=$(mktemp -d)
git init -b main "$workdir/project"
cd "$workdir/project"
git config user.name 'Workshop Learner'
git config user.email 'learner@example.invalid'Identity configuration is written only to this repository, and does not use --global. This chapter uses git init -b, git switch, and git restore, which require Git 2.28 or higher version; -b main explicitly specifies the initial branch name, and the result is not affected by machine default configurations.
printf '%s\n' '# Workshop Project' > README.md
printf '%s\n' "print('hello')" > main.py
git status --short?? indicates untracked files. Git has not added them to a commit. The next git diff may print nothing because ordinary diff does not show untracked file contents. After staging, git diff --staged shows both new files.
Staging and Committing
git diff
git add README.md main.py
git diff --staged
git commit -m 'Initialize workshop project'
git status
git log --oneline --decorateAfter the first commit, changes can be located using the three-layer model:
Working Directory -- add --> Staging Area (index) -- commit --> Commit referenced by HEAD- The working directory is the current set of editable files.
- The staging area describes what will be saved in the next commit.
HEADtypically points to the current branch, and the current branch points to a specific commit.
git add . only processes paths below the current directory and may accidentally include logs or keys. In the early stages, run git status --short and git diff first, then specify individual files. When you need to split different changes within a single file, use git add -p.
Commits Use a Snapshot Model
A commit records the project tree, parent commit, author and committer information, and the message. Git reuses the same objects, so "snapshot" describes the observation method, not that a full disk directory is copied every time.
git show --stat --oneline HEAD
git show HEAD:README.mdThe commit message should help later readers understand the purpose of the changes. After completing this page, keep $workdir for now, and use it in the following chapters; if you stop practicing, leave the directory and delete it after checking the path.