AI Hints
Home›Linux Tutorial›More Projects
Linux · Lesson 114 of 120

Project: Disk Cleanup

Find the space hogs.

⏱ 2 min read▶ Video at 2:32:41🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

Disk full! It happens to everyone. Usually a few huge files are to blame. An old download, a forgotten video. Let's find them, and safely clean them up, with a script that asks before deleting anything.

Project: Disk Cleanup
From the video: Project: Disk Cleanup
  • Disk full!
  • A few huge files
  • Find them, ask, then delete

Finding the hogs

DU dash SH, star, shows the size of each folder in home. Sort dash H sorts human sizes properly, biggest last. Downloads is the problem. Then find dash size plus one hundred M finds every file over one hundred megabytes.

Terminal
du -sh --apparent-size * | sort -h
18      Music
30      notes.txt
58      todo.txt
54K     Pictures
81M     Documents
822M    Downloads
find ~ -type f -size +100M
/home/sam/Downloads/ubuntu.iso
/home/sam/Downloads/old-movie.mp4

cleanup.sh

The script takes a folder, or uses home. It lists every file over one hundred megabytes, with its size. Then it asks before doing anything. Only if the answer is Y, find dash delete removes them.

nano cleanup.shbash
#!/bin/bash
dir="${1:-$HOME}"
echo "Files over 100 MB in $dir:"
find "$dir" -type f -size +100M -exec ls -lh {} \; | awk '{print $5, $9}'
read -p "Delete them? (y/n) " answer
if [ "$answer" = "y" ]; then
  find "$dir" -type f -size +100M -delete
  echo "Deleted."
else
  echo "Nothing deleted."
fi

Clean up, safely

We run the cleanup on Downloads. Two big files. We answer Y, and they're deleted. DU shows Downloads is tiny again.

Terminal
./cleanup.sh Downloads
Files over 100 MB in Downloads:
700M Downloads/ubuntu.iso
120M Downloads/old-movie.mp4
Delete them? (y/n) y
Deleted.
du -sh --apparent-size Downloads
2.0M    Downloads

Summary

DU and sort dash H find the big folders, find dash size finds the big files, and our script asks before deleting. Next, a new section. Fixing the most common Linux errors.

Key takeaways
  • du -sh * | sort -h
  • find -size +100M
  • Ask before deleting
Next up: Troubleshooting — common errors and fixes