brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: du --apparent-size explains why ls and du disagree about a file

Disk usage
~/tips/tip-du-apparent-size-sparse-files

truncate -s 10G test.img

Shows the size a file claims to be next to the space it really uses on disk.

ls -l says a file is 10 GB, du -h says it takes almost nothing. Neither is lying. They measure two different things, and du has a flag to show you the other number.

By default du reports how much space a file really takes on the disk. ls shows the apparent size: the number of bytes you’d get when you read the file from start to end. With --apparent-size du shows that second number too:

truncate -s 10G test.img
du -h test.img
du -h --apparent-size test.img

truncate creates a sparse file here: 10 GB long, but with no data blocks behind it yet. The first du gives you about 0, the second one 10G. You’ll run into the same thing with virtual disk images for VMs and with some database and download files that reserve their full length up front. The disk space only gets used once real data is written into those holes. du -b is a shortcut for the apparent size in bytes.

It also works the other way round. A folder full of tiny files often takes more space on disk than the apparent size says, because every file uses at least one block. So when a share is fuller than the sizes of its files add up to, comparing du -sh with du -sh --apparent-size on the same folder is the first thing I’d do.

The caveat: sparse files don’t always stay sparse. Copy one with a tool that ignores the holes and the copy takes the full 10 GB. GNU cp tries to keep files sparse by default, but with rsync you have to ask for it with --sparse. Check the target with plain du after a copy like that.

Further reading: du invocation (GNU coreutils), du(1) manual page

More Disk usage tips du -sh — .[!.]* * 2>/dev/null | sort -h du -h -t 1G /srv | sort -h du -ch /var/log/*.log | tail -n 1 du -sh --exclude=node_modules --exclude='*.iso' ~/projects df -h --output=source,fstype,size,used,avail,pcent,target All Disk usage tips (18) All topics

Link