Initializing a Git Repository: A Detailed Explanation of the `git init` Command and the .git Directory Structure
A Git repository is at the heart of version control; all code history, branches, and tags are stored in the repository. This lesson provides a detailed explanation of how to create and manage repositories.
1. Overview of Git Repositories
A Git repository is a database that contains all the files in a project and their complete history.
(1) What is a Git repository?
A Git repository is a directory that contains project files and version history. It has the following characteristics:
- Complete History: Records a complete snapshot of every commit
- Branch Support: You can create multiple parallel development branches
- Distributed: Each repository is independent and contains the complete history
- Efficient Storage: Saves space using compression and deduplication technologies
(2) Two Ways to Create a Repository
graph TB
A[CreateGitWarehouse] --> B[git init<br/>Create a New Repository from Scratch]
A --> C[git clone<br/>Clone a Remote Repository]
B --> D[Empty Warehouse<br/>You need to add the files manually.]
C --> E[Complete Repository<br/>Includes all historical data]
style A fill:#e1f5ff
style B fill:#fff4e1
style C fill:#fff4e1
The Difference Between the Two Methods:
| Method | Command | Applicable Scenarios | Includes History |
|---|---|---|---|
| Initialization | git init |
Create a new project | ❌ Empty repository |
| Clone | git clone |
Join an existing project | ✅ Full history |
2. Initialize a repository with git init
The git init command converts a regular directory into a Git repository.
(1) Initialization Process
graph LR
A[Create a Directory] --> B[Go to the Table of Contents]
B --> C[Run git init]
C --> D[Create .git Table of Contents]
D --> E[The warehouse was successfully created.]
style A fill:#e1f5ff
style E fill:#d4edda
(2) Basic Usage
# Method1:Initialize in the current directory
cd my-project
git init
# Method2:Create and initialize a new directory
git init my-project
▶ Example: Creating a New Repository
# Steps1:Create a project directory
mkdir my-project
# Steps2:Go to the Table of Contents
cd my-project
# Steps3:InitializationGitWarehouse
git init
# Output:
# Initialized empty Git repository in /path/to/my-project/.git/
# Steps4:View Repository Status
git status
# Output:
# On branch main
# No commits yet
# nothing to commit (create/copy files and use "git add" to track)
# Steps5:View the directory structure
ls -la
# Output:
# total 0
# drwxr-xr-x 3 user group 4096 Jan 1 00:00 .
# drwxr-xr-x 3 user group 4096 Jan 1 00:00 ..
# drwxr-xr-x 7 user group 4096 Jan 1 00:00 .git
(3) Initialize in an existing project
If you already have a project file, you can initialize it directly in the project directory:
# Go to the directory of the existing project
cd existing-project
# InitializationGitWarehouse
git init
# View Status(All existing files are untracked.)
git status
# Output:
# Untracked files:
# src/
# README.md
# package.json
git init does not modify existing files; it simply creates the .git directory. All existing files will become "Untracked."
3. .git Directory Structure
.git The directory is the core of a Git repository and stores all version control information.
(1) Detailed Explanation of the Directory Structure
.git/
├── HEAD # Current branch pointer
├── config # Local Configuration File
├── description # Repository Description (for GitWeb)
├── hooks/ # Hook Scripts Directory
│ ├── pre-commit.sample
│ └── post-commit.sample
├── info/ # Additional Information
│ └── exclude # Local Ignore Rules
├── objects/ # All Data Objects (Commits, Trees, Documents)
│ ├── info/
│ └── pack/
├── refs/ # Quote(Branch、Tags)
│ ├── heads/ # Local Branch
│ └── tags/ # Tags
└── index # Buffer Information(Documents)
(2) Notes on Important Documents
| File/Directory | Description | Sample Content |
|---|---|---|
| HEAD | Points to the current branch | ref: refs/heads/main |
| config | Local configuration | Remote repository address, user information, etc. |
| objects/ | Stores all data objects | Commits, trees, file snapshots (stored in compressed form) |
| refs/heads/ | Local branch pointer | One file per branch, containing the commit hash |
| refs/tags/ | Tag pointers | One file per tag |
| index | Stash Information | Records the status of files in the stash |
▶ Example: Viewing the .git directory
# Steps1:View.gitTable of Contents
ls -la .git
# Output:
# -rw-r--r-- 1 user group 23 Jan 1 00:00 HEAD
# -rw-r--r-- 1 user group 137 Jan 1 00:00 config
# -rw-r--r-- 1 user group 73 Jan 1 00:00 description
# drwxr-xr-x 2 user group 4096 Jan 1 00:00 hooks
# drwxr-xr-x 2 user group 4096 Jan 1 00:00 info
# drwxr-xr-x 4 user group 4096 Jan 1 00:00 objects
# drwxr-xr-x 4 user group 4096 Jan 1 00:00 refs
# Steps2:ViewHEADDocuments
cat .git/HEAD
# Output:ref: refs/heads/main
# Steps3:View Profile
cat .git/config
# Output:
# [core]
# repositoryformatversion = 0
# filemode = true
# bare = false
# logallrefupdates = true
# Steps4:View the branch directory
ls -la .git/refs/heads
# Output:(Initially empty,After creating a commit, there will bemainDocuments)
(3) Detailed Explanation of the "objects" Directory
objects The repository stores all Git data objects, using SHA-1 hashes as filenames:
objects/
├── 4a/ # Before hashing2"as" as the directory name
│ └── 8b2f... # After hashing38"as" as the filename
├── info/
└── pack/ # Packaging and Storage(Space-saving)
Object Type:
- Blob: File content
- Tree: Directory structure
- Commit: Commit message
- Tag: Tag information
.git directory unless you are absolutely sure of what you are doing! Incorrect modifications may result in repository corruption.
4. Cloning a Repository with git clone
The git clone command is used to clone a remote repository to your local machine.
(1) The Role of Cloning
Cloning performs the following operations:
- Download Full History: Includes all commits, branches, and tags
- Create a local repository: Create a
.gitdirectory on your local machine - Automatically Link Remote: Create a remote reference named
origin - Default branch: Usually
mainormaster
(2) Clone Command Syntax
# Basic Syntax
git clone <Warehouse Address>
# Clone to the specified directory
git clone <Warehouse Address> <Directory Name>
# Shallow Cloning(Clone Only RecentNNext Submission)
git clone --depth <In-Depth> <Warehouse Address>
# Clone a Single Branch
git clone -b <Branch Name> --single-branch <Warehouse Address>
▶ Example: Cloning a GitHub Repository
# Method1:UsageHTTPSClone(Recommended for Beginners)
git clone https://github.com/user/repo.git
# Output:
# Cloning into 'repo'...
# remote: Enumerating objects: 100, done.
# remote: Counting objects: 100% (100/100), done.
# remote: Compressing objects: 100% (80/80), done.
# remote: Total 100 (delta 20), reused 100 (delta 20), pack-reused 0
# Receiving objects: 100% (100/100), done.
# Resolving deltas: 100% (20/20), done.
# Method 2: Use SSH Clone (requires SSH key configuration)
git clone git@github.com:user/repo.git
# Method3:Clone to the specified directory
git clone https://github.com/user/repo.git my-project
# Method4:Shallow Cloning(Clone Only Recent1Next Submission,Fast)
git clone --depth 1 https://github.com/user/repo.git
# Steps:Verify the cloning results
cd repo
git remote -v
# Output:
# origin https://github.com/user/repo.git (fetch)
# origin https://github.com/user/repo.git (push)
(3) Directory Structure After Cloning
graph TB
A[Remote Repository<br/>github.com/user/repo] --> B[git clone]
B --> C[Local Warehouse]
C --> D[.git Table of Contents<br/>Complete History+Remote Configuration]
C --> E[Project Documents<br/>The latest version of the default branch]
D --> F[origin Remote References]
style A fill:#e1f5ff
style C fill:#d4edda
origin pointing to the original repository address. You can view it using git remote -v.
5. Viewing Warehouse Status
git status is the basic command for checking the current status of a repository.
(1) File Status Types
graph LR
A[Document Status] --> B[Not tracked<br/>Untracked]
A --> C[Modified<br/>Modified]
A --> D[Saved<br/>Staged]
A --> E[Submitted<br/>Committed]
B -->|git add| D
C -->|git add| D
D -->|git commit| E
E -->|Edit File| C
style B fill:#fff3cd
style C fill:#ffe6e6
style D fill:#d4edda
style E fill:#c3e6cb
(2) Status Description Table
| Status | English Name | Description | Next Action |
|---|---|---|---|
| Not tracked | Untracked | New file, not tracked by Git | git add Added to staging area |
| Modified | Modified | Tracked file has been modified but not staged | git add Added to staging area |
| Staged | Staged | Added to staging, ready to be committed | git commit Commit |
| Committed | Committed | Committed to the local repository | Continue working or push |
▶ Example: Checking the repository status
# Steps1:Initialize the repository
mkdir demo && cd demo
git init
# Steps2:View Initial State(Empty Warehouse)
git status
# Output:
# On branch main
# No commits yet
# nothing to commit (create/copy files and use "git add" to track)
# Steps3:Create a New File
echo "# Demo Project" > README.md
# Steps4:View Status(Not tracked)
git status
# Output:
# On branch main
# No commits yet
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
# README.md
# nothing added to commit but untracked files present
# Steps5:Add to Stash
git add README.md
# Steps6:View Status(Saved)
git status
# Output:
# On branch main
# No commits yet
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
# new file: README.md
# Steps7:Submit
git commit -m "Initial commit"
# Steps8:View Status(Clean)
git status
# Output:
# On branch main
# nothing to commit, working tree clean
(3) Status Overview
Use the -s option to view a concise status output:
git status -s
# Output Example:
# M modified-file.txt # Modified(On the leftMIndicates a temporary storage area,on the rightMIndicates workspace)
# A new-file.txt # New files that have been cached
# ?? untracked-file.txt # Untracked files
❓ FAQ
git init and git clone?git init creates a brand-new, empty repository, which is suitable for new projects; git clone copies an existing remote repository (including its complete history), which is suitable for joining an existing project.git init directly in the directory. Git will not modify any existing files; it will simply create a .git directory. All existing files will be marked as untracked.git clone --depth 1 <url>, which clones only the most recent commit and is faster. This is suitable for scenarios where you only need the latest code and don’t need the history.📖 Summary
- A Git repository is the core of version control; it contains project files and a complete history.
- There are two ways to create a repository:
git init(New) andgit clone(Clone) - The
.gitdirectory stores all version control information, including HEAD, config, objects, refs, and more. - Cloning downloads the entire history, creates a local repository, and automatically links to the remote "origin"
- Files have four states: untracked, modified, staged, and committed
- Use
git statusto check the repository status and see which stage the file is in
📝 Exercises
-
Basic Exercise (Difficulty: ⭐): Create a Git repository named
my-first-repo, examine the directory structure of.git, and explain the purpose of the HEAD file. -
Advanced Exercise (Difficulty ⭐⭐): Create a README.md file and a src directory in the repository. Use
git statusto observe changes in the file statuses, and record the meaning of each status. -
Challenge (Difficulty: ⭐⭐⭐): Clone a public GitHub repository (e.g., https://github.com/octocat/Hello-World.git), review the remote configuration (
git remote -v), and explain the meaning and purpose oforigin.



