Creating Sparse Disk Images with Multiple EXT4 Partitions

Abstract: Create a single sparse disk image with multiple EXT4 partitions using truncate, fdisk, and losetup.

Created: 2026-08-24 by

You can create a single sparse disk image containing multiple EXT4 partitions by allocating a large file with truncate, defining partition boundaries with fdisk, mapping those partitions to loop devices using losetup, and formatting each slice independently with mkfs.ext4. This approach yields one cohesive binary file that behaves like a physical hard drive.

Allocating the Sparse Image File

The foundation of this process is a single file that reserves space on your host filesystem without immediately writing data to the disk blocks. This is known as a sparse file. Using the truncate command allows you to specify the total capacity of the virtual disk instantly. For example, creating a 10-gigabyte image takes less than a second regardless of your current disk speed because no actual data is written yet. You should choose a size that accommodates all your intended partitions plus some overhead for bootloaders or metadata. A common setup involves a small boot partition and a larger root partition. To create a 10GB sparse file named disk.img, run:
truncate -s 10G disk.img
Verify the creation with ls -lh disk.img. You will see the reported size as 10G, but the actual disk usage (shown in the last column) might be significantly lower, often just a few kilobytes. This confirms the file is sparse. If you were to write data to this file later, the kernel would allocate blocks dynamically. This efficiency is crucial when dealing with large images where most space remains empty initially.

Defining Partition Layouts

A raw image file does not have a partition table until you explicitly define one. You must use a partitioning tool to carve the single file into distinct logical sections. The standard utility for this is fdisk. Because you are working with a file rather than a physical block device, you pass the filename directly to the command. Start fdisk on your image:
sudo fdisk disk.img
Inside the interactive prompt, press n to add a new partition. Accept the default first sector, then specify the size for the first partition. For a boot partition, a size of +512M is usually sufficient. Press p to print the table and verify the start and end sectors. Then, create a second partition for the root filesystem by pressing n again. Accept the defaults to use the remaining space. Finally, press w to write the changes and exit. It is important to note that these commands only modify the partition table metadata within the file. No filesystem structures are created yet. The image now contains two "partitions," but they are just ranges of bytes. To interact with them as filesystems, you need to map these ranges to kernel loop devices.

Mapping Partitions to Loop Devices

Linux provides loop devices that allow files to be accessed as block devices. However, since our image has multiple partitions, we cannot simply use losetup on the whole file. We need to tell the kernel exactly which offset and size correspond to each partition. First, identify the offsets created by fdisk. You can do this by running sfdisk -d disk.img. This outputs a script-like format showing the start sector and size for each partition. Calculate the byte offset by multiplying the start sector by the sector size (usually 512 bytes). For example, if the first partition starts at sector 2048, the offset is 2048 * 512 = 1048576 bytes. Use losetup with the -o (offset) and --sizelimit flags to attach specific slices:
sudo losetup -f --show -o 1048576 --sizelimit 536870912 disk.img
This command attaches the first 512MB slice to the next available loop device, likely /dev/loop0. Repeat this process for the second partition, adjusting the offset and size accordingly. You might get /dev/loop1. Verify the mappings with losetup -l. Now, /dev/loop0 represents the boot partition, and /dev/loop1 represents the root partition.

Formatting with EXT4

With the partitions mapped to separate loop devices, you can treat them exactly like physical drives. Use mkfs.ext4 to create the filesystem on each device. Format the boot partition:
sudo mkfs.ext4 /dev/loop0
Format the root partition:
sudo mkfs.ext4 /dev/loop1
These commands initialize the superblocks, inode tables, and block groups for each partition. The resulting disk.img now contains a valid MBR partition table and two distinct EXT4 filesystems. You can detach the loop devices with sudo losetup -d /dev/loop0 and sudo losetup -d /dev/loop1 when finished. This method ensures that tools expecting a single disk image, such as QEMU or KVM, can boot from it seamlessly. It also simplifies backup procedures since you only manage one file instead of multiple scattered partition images. For more information on maintaining ext4 integrity, see Recovering inode connection on ext4 fs.

Frequently Asked Questions

Can I resize the partitions after creation?

Yes, but it requires careful manipulation. You must remap the loop devices with updated offsets and sizes, then use resize2fs on the mapped device before resizing the partition table in fdisk. Always back up the image first.

How do I mount these partitions on my host system?

Use mount with the -o loop,offset=... option. Specify the exact byte offset and sizelimit in the mount command to access the contents of a specific partition within the single image file.

What happens if I lose power during formatting?

If power is lost while mkfs.ext4 is writing, the filesystem may become corrupted. You can attempt to repair it using e2fsck on the mapped loop device. See Fixing EXT4 Filesystem Superblock Invalid Error After lvextend and Power Failure for details on superblock issues.

Is there a limit to how many partitions I can create?

The primary limit is defined by the partition table type. With MBR, you are limited to four primary partitions. GPT supports up to 128 partitions. Ensure you use gdisk instead of fdisk if you need more than four partitions.

Why is my sparse image taking up full disk space?

If you copy the image using cp without preserving sparse attributes, the zeros may be filled with actual data blocks. Use cp --sparse=always or rsync to maintain the sparse nature of the file.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More