To create a sparse file on APFS (Apple File System) using the command line on macOS, you can use the dd and truncate commands. A sparse file is a file that appears larger than it actually is, with "holes" where data isn't stored, saving disk space. Here's how to do it:
Method 1: Using dd and truncate
This method creates a sparse file by first writing a small amount of data and then expanding the file size using truncate.
bash
# Step 1: Create a small file with 1MB of zeros
dd if=/dev/zero of=sparsefile bs=1M count=1
# Step 2: Expand the file to 10GB, creating a sparse file
truncate -s 10G sparsefile
Explanation:
dd if=/dev/zero of=sparsefile bs=1M count=1: Creates a 1MB file filled with zeros.
truncate -s 10G sparsefile: Expands the file size to 10GB. Since APFS supports sparse files, the file will appear as 10GB but only use ~1MB of actual disk space.
Method 2: Using mkfile (if supported)
On some systems, mkfile can create sparse files directly. However, macOS's mkfile does not support sparse files by default. If you're using a system where mkfile does support sparse files (e.g., Linux), you can use:
bash
mkfile -s 10G sparsefile
But on macOS, this will not create a sparse file. Use Method 1 instead.
Verification
To confirm the file is sparse, check its logical size and actual disk usage:
bash
# Check file size (logical size)
ls -l sparsefile
# Check actual disk usage (physical size)
du -h sparsefile
A sparse file will show a large logical size (e.g., 10G) and a small physical size (e.g., 4.0K or 1MB).
Alternative: Sparse Disk Image (Optional)
If you need a disk image (e.g., for mounting), use hdiutil: