L7: Git Clone and Extracting the Kernel Source Tree

← Previous Lecture
Chapter 2  |  Lecture 7
Next Lecture →

Free Linux Kernel Programming Course  |  Chapter 2

Git Clone and Extracting the Kernel Source Tree

Two ways to get the kernel onto your machine — plus how to set up a clean workspace

⏱ ~20 min read
🔧 Hands-on Terminal
🐧 Kernel 6.x / 7.x (2026)

What You Will Learn

  • The difference between cloning via Git and downloading a tarball
  • How to clone the mainline Linux kernel Git tree
  • What a shallow clone is and how it saves gigabytes of disk space
  • What the linux-next tree is and whether you need it
  • How to extract the kernel source using tar
  • How to organize a proper workspace for kernel development
  • How to set an environment variable for your kernel source path
  • Why you should never extract the kernel into /usr/src/

Topics Covered

git clone linux kernel
shallow clone
linux-next tree
tar xf kernel
kernel source extraction
KDIR environment variable
linux kernel workspace
free linux device drivers course

The Two Paths — Git Clone vs Tarball

In the previous lecture we saw how to download a kernel tarball. Now we look at two complete paths to get the kernel source onto your machine and ready to build. The path you choose depends on what you plan to do with the kernel.

Two Ways to Get the Linux Kernel Source

PATH A — Tarball Download
————————-
Download .tar.xz –> Extract with tar –> Source ready to buildBest for:
– Learning a specific kernel version
– Building for an embedded product
– Students following this course
– No Git knowledge requiredPATH B — Git Clone
——————
git clone –> Directory created automatically –> Source ready to buildBest for:
– Contributing patches upstream
– Developers who need full commit history
– Switching between kernel versions easily
– Tracking changes over timeBoth paths give you the same end result:
a directory full of kernel source files, ready to configure and build.

1. Cloning the Linux Kernel via Git

When you run git clone on the kernel repository, you are not just downloading the source files. You are downloading the entire history of every change ever made to Linux — decades of commits from thousands of developers worldwide.

There are multiple Git trees in the Linux kernel ecosystem. Understanding the hierarchy helps you pick the right one:

Linux Kernel Git Tree Hierarchy

linux-next (daily integration tree)
|
| Subsystem maintainers send patches here first.
| Updated every day. May not even compile.
| Only for contributors — DO NOT use for learning.
|
v
mainline (Linus Torvalds’ official tree)
|
| All official releases come from here.
| Stable enough to build and study from.
| Use this for learning and development.
|
v
stable / LTS trees (maintained by Greg KH and others)
|
| Bug fixes and security patches backported from mainline.
| Used in production, Android, and embedded systems.
| Best base for any product that ships to customers.

Cloning the Mainline Kernel Tree

The mainline tree is Linus Torvalds’ personal tree. All official kernel releases originate here. For anyone learning Linux kernel programming or Linux device driver development, this is the right Git tree to clone:

# Clone the full mainline Linux kernel tree
# WARNING: This downloads several gigabytes of data
git clone https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

⚠️ Disk Space Warning

A full clone of the Linux kernel tree can download several gigabytes of data. The .git folder alone can reach 3 to 4 GB because it stores the complete commit history going back to 1991. Ensure you have at least 10 GB free before running a full clone.

2. The Right Way — Shallow Clone

For learning kernel programming, you do not need 30 years of commit history. You just need the latest code. A shallow clone lets you download only the most recent commits instead of the entire history. This saves enormous amounts of time and disk space.

Full Clone vs Shallow Clone — Size Comparison

FULL CLONE (git clone without –depth)
—————————————-
HEAD <– commit from June 2026
commit from May 2026
commit from April 2026
… (thousands more) …
commit from 2000
commit from 1991 (the very first Linux commit!)Download size: ~3 to 5 GB
Time on average connection: 30 to 90 minutesSHALLOW CLONE (git clone –depth=3)
—————————————-
HEAD <– commit #3 (most recent)
commit #2
commit #1 (shallow boundary — history stops here)Download size: ~400 to 800 MB
Time on average connection: 5 to 15 minutesFor learning: shallow clone is the correct choice.

Here is how to do a shallow clone with only the last 3 commits of history:

# Shallow clone — downloads only the 3 most recent commits
# This is the recommended approach for students and developers
git clone --depth=3 \
  https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

💡 What happens after a shallow clone?

Git automatically creates a directory called linux/ in your current folder and places all source files inside it. The source is already extracted and ready to use. You do not need to run any tar commands — skip straight to the configuration step.

3. What Is linux-next and Should You Use It?

You will hear linux-next mentioned often in kernel development discussions. Here is the plain explanation of what it is and who actually needs it.

The Linux kernel development cycle works like this: Linus Torvalds opens a merge window for about two weeks, during which subsystem maintainers submit their patches. Before those patches land in Linus’s mainline tree, they all get merged into linux-next — a tree that acts as the kernel’s pre-integration test environment. It is rebuilt and updated every day.

Because linux-next pulls in patches from dozens of subsystems simultaneously, it is inherently unstable. It may fail to compile, fail to boot, or behave unpredictably on any given day. It exists purely as a testing ground, not as a usable kernel.

📌 Simple rule for choosing your Git tree

If you are learning kernel programming or writing device drivers → clone the mainline tree (Torvalds) or download an LTS tarball.

If you are submitting patches upstream → you need linux-next so your patch applies cleanly against what is queued for the next merge window.

4. Extracting the Kernel Source Tarball

If you followed Path A from the previous lecture and downloaded a .tar.xz tarball, you now need to extract it. The tar command handles this.

Simple Extraction — Into the Current Directory

# Extracts into a folder named linux-6.12/ inside ~/Downloads/
tar xf ~/Downloads/linux-6.12.tar.xz

What the tar Flags Mean

Flag Full Name What It Does
x extract Extract the files from the archive.
f file The next argument is the archive filename. Without this, tar reads from stdin.

You do not need to add -J for xz or -z for gzip. Modern tar automatically detects the compression format from the file header, so tar xf works universally regardless of compression type.

Better Practice — Extract Into a Dedicated Kernels Folder

Scattering kernel source directories inside ~/Downloads gets messy fast. The cleaner approach is to keep all your kernel sources in a dedicated directory:

# Step 1: Create a dedicated kernels folder
mkdir -p ~/kernels

# Step 2: Extract the tarball directly into it
tar xf ~/Downloads/linux-6.12.tar.xz --directory=${HOME}/kernels/

# Your kernel source is now at: ~/kernels/linux-6.12/

The --directory flag tells tar to place all extracted files inside that target folder instead of the current working directory. The -p flag in mkdir means: create parent directories as needed, and do not fail if the folder already exists.

5. Setting the KDIR Environment Variable

This is one small habit that pays off constantly in kernel development. The path to your kernel source tree appears in dozens of places — build commands, Makefiles, grep searches, and cross-compilation setups. Instead of typing the full path every time, set it once as an environment variable:

# Point KDIR at your kernel source tree
export KDIR=${HOME}/kernels/linux-6.12

# Verify it was set correctly
echo $KDIR
# Expected output: /home/yourname/kernels/linux-6.12

# Confirm the source is there
ls $KDIR
# Should show: Makefile  arch  block  certs  crypto  drivers  fs  ...

# Now use it in build commands like:
make -C $KDIR M=$(pwd) modules

💡 Make KDIR permanent across sessions

The export command only lasts for the current terminal session. To make it permanent, add the line to your shell configuration file and then reload it:

# For bash users:
echo 'export KDIR=${HOME}/kernels/linux-6.12' >> ~/.bashrc
source ~/.bashrc

# For zsh users:
echo 'export KDIR=${HOME}/kernels/linux-6.12' >> ~/.zshrc
source ~/.zshrc

6. Recommended Directory Layout for Kernel Development

When you work with multiple kernel versions over time — and in embedded development you almost always do — having a consistent folder structure prevents confusion and mistakes.

~/kernels/
├── linux-6.12/          LTS kernel — for production or embedded work
├── linux-6.18/          Newer LTS kernel — for testing newer APIs
├── linux-7.0/           Latest stable — for learning new features
├── linux/               Git clone of mainline (kept updated with git pull)
│
~/kernel-modules/        Your own kernel module source code goes here
~/kernel-builds/         Out-of-tree build output goes here

The key principle is to keep your own code inside kernel-modules/, completely separate from the kernel source inside kernels/. You should never modify files inside the kernel source tree when you are just writing a module — the kernel source should remain a clean, unmodified reference.

7. Why You Should Not Use /usr/src/ Anymore

If you read older Linux kernel books or tutorials from the 2000s, they tell you to put the kernel source inside /usr/src/linux/. This practice is outdated and you should avoid it.

Old Way vs Modern Way

Approach Location Problems
Old way (avoid) /usr/src/linux-6.12/ Needs sudo to write. System-wide. One version at a time. Risk of breaking system headers.
Modern way (use this) ~/kernels/linux-6.12/ No root needed. Multiple versions in parallel. No risk to system. Easy to delete or replace.

The core reason for the change is simple: you should not need root privileges just to read or compile kernel source code. When everything lives inside your home directory, you have full read-write access without sudo, you can maintain multiple kernel versions side by side without conflict, and an accidental rm -rf only affects your home directory, not critical system paths.

8. Complete Workflow — From Zero to Kernel Source Ready

Here is the full sequence for both paths, from an empty terminal to a kernel source tree ready to configure and build:

## PATH A: Tarball Workflow ##

# 1. Download kernel 6.12 LTS (update version as newer LTS releases)
wget --https-only \
     -O ~/Downloads/linux-6.12.tar.xz \
     https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.12.tar.xz

# 2. Create kernels directory
mkdir -p ~/kernels

# 3. Extract into it
tar xf ~/Downloads/linux-6.12.tar.xz --directory=${HOME}/kernels/

# 4. Set environment variable
export KDIR=${HOME}/kernels/linux-6.12

# 5. Verify — you should see Makefile, arch/, drivers/, etc.
ls $KDIR


## PATH B: Git Clone Workflow ##

# 1. Go to your kernels directory
mkdir -p ~/kernels && cd ~/kernels

# 2. Shallow clone — much faster than a full clone
git clone --depth=3 \
  https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

# 3. Set environment variable
export KDIR=${HOME}/kernels/linux

# 4. Verify
ls $KDIR

✅ How to confirm the extraction or clone worked

Run ls $KDIR. If you see a file called Makefile alongside directories like arch/, kernel/, and drivers/, everything is correct and you are ready to proceed to kernel configuration.

📋 Key Takeaways — Lecture 7

#128203; Key Takeaways — Lecture 7

  • Two ways to get the kernel source: tarball download or git clone
  • Use --depth=3 with git clone to save gigabytes of download and disk space
  • linux-next is for upstream contributors only — do not use it for learning
  • Extract tarballs with tar xf file.tar.xz --directory=TARGET_FOLDER
  • Always extract into your home directory — never into /usr/src/
  • Set export KDIR=~/kernels/linux-VERSION and persist it in .bashrc
  • After extraction, check for Makefile and arch/ to confirm success
  • Keep your own module code in a separate folder — never modify the kernel source tree directly

🎯 Interview Questions — Git Clone and Kernel Extraction

#127919; Interview Questions — Git Clone and Kernel Extraction

Q1. What is the difference between downloading a kernel tarball and doing a git clone?

Answer: A tarball is a fixed snapshot of the kernel source at a specific version — you get the files but no history. A git clone downloads the full repository including the complete commit history. With Git you can switch branches, create patches, and track changes over time. For learning a fixed version, a tarball is simpler. For contributing patches upstream, a git clone is mandatory.

Q2. What is a shallow clone and when would you use it?

Answer: A shallow clone using git clone --depth=N downloads only the last N commits instead of the entire history. For the Linux kernel, a full history is several gigabytes. A shallow clone with depth 1 or 3 gets you the latest source in a fraction of the download size and time. Use it when you want to build or study the kernel without needing historical commits.

Q3. How do you extract a .tar.xz file into a specific directory?

Answer: Use tar xf filename.tar.xz --directory=/target/path/. The x flag means extract, f means the next argument is the filename, and –directory specifies where to put the extracted contents. Modern tar detects the compression format automatically — you do not need to add -J for xz files.

Q4. Why should you not extract the kernel source into /usr/src/?

Answer: /usr/src/ is a system directory that requires root access to write to. Modern practice is to work entirely inside your home directory where you have full permissions without sudo. This allows multiple kernel versions to coexist, eliminates the need for elevated privileges during normal development, and prevents any accidental corruption of system-level paths.

Q5. What is the purpose of the KDIR environment variable in kernel development?

Answer: KDIR holds the path to your kernel source tree. When building out-of-tree modules, the standard make invocation is make -C $KDIR M=$(pwd) modules. Using a variable means you type the path once and reference it everywhere. It also makes Makefiles portable — switching kernel versions only requires changing KDIR rather than editing every command in your build scripts.

Q6. What is linux-next and how does it differ from the mainline kernel tree?

Answer: linux-next is a daily integration tree where patches from all kernel subsystem maintainers are merged together to test for conflicts before entering Linus Torvalds’ mainline tree. It is updated every day and may not compile or boot reliably. The mainline tree only accepts new code during the merge window (about 2 weeks per release cycle), then only bug fixes until release. Mainline is stable enough to build from; linux-next is not.

Q7. After running git clone on the kernel, do you still need to run tar to extract it?

Answer: No. When git clone completes, it automatically creates a directory and populates it with all source files — extraction happens as part of the clone operation. The tar extraction step is only needed for the tarball download path. These are two independent workflows: git clone is self-contained, while the tarball download requires a separate extraction step.

Continue the Free Linux Kernel Programming Course

Next lecture covers configuring the Linux kernel — menuconfig, defconfig, and understanding the .config file.

← Previous Lecture
EmbeddedPathashala — Free Embedded Systems Education
Next Lecture →

Leave a Reply

Your email address will not be published. Required fields are marked *