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:

(2) Two Ways to Create a Repository

100%
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

100%
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

BASH
# 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

BASH
# 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:

BASH
# 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
💡 Tip: 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

TEXT
.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

BASH
# 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:

TEXT
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:

⚠️ Note: Do not manually modify files in the .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:

  1. Download Full History: Includes all commits, branches, and tags
  2. Create a local repository: Create a .git directory on your local machine
  3. Automatically Link Remote: Create a remote reference named origin
  4. Default branch: Usually main or master

(2) Clone Command Syntax

BASH
# 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

BASH
# 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

100%
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
💡 Tip: Cloning automatically creates a remote connection 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

100%
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

BASH
# 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:

BASH
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

Q What is the difference between git init and git clone?
A 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.
Q Can I delete the .git directory?
A Yes, but this will delete the entire version history! After deletion, the directory will become a regular directory and will no longer be a Git repository. You should only delete it if you are certain you no longer need the version history.
Q How do I initialize a repository in a directory that already contains files?
A Run 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.
Q What should I do if cloning a repository is slow?
A You can use a shallow clone 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


📝 Exercises

  1. 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.

  2. Advanced Exercise (Difficulty ⭐⭐): Create a README.md file and a src directory in the repository. Use git status to observe changes in the file statuses, and record the meaning of each status.

  3. 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 of origin.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏