I know every system administrator faces this issue of unknowing Disk space consumption; this is a nightmare ☹
So being a lazy system administrator, I tried to write a script that I could run against any directory, and it provides output for the top 20 disk space consumers; I could uplift this number as well.
Here is the script:
#!/bin/bash
# Prompt for the directory to analyze
echo "Enter the directory to analyze (default: current directory):"
read DIR# Set default directory if none provided
DIR=${DIR:-.}
# Check if the directory exists
if [ ! -d "$DIR" ]; then
echo "Error: Directory '$DIR' does not exist."
exit 1
fi
# Find and display the top 20 largest files/directories
echo "Analyzing the top 20 largest files or directories in '$DIR'..."
du -ah "$DIR" 2>/dev/null | sort -rh | head -n 20
How to Use the Script
- Save the script as top20_size.sh.
- Make it executable:
chmod +x top20_size.sh
- Run the script
./top20_size.sh
- When prompted, enter the directory you want to analyze. If you press Enter without typing anything, it will default to the current directory.
Explanation
- du -ah “$DIR”: Calculates the sizes of files and directories in human-readable format (-h) and includes hidden files (-a).
- sort -rh: Sorts the sizes in reverse order (-r) and interprets human-readable sizes correctly (-h).
- head -n 20: Displays the top 20 entries.
This script can be customized as per requirement. You can add more logic—email the output if the total size exceeds some GB or percentage. Put this in the cron to execute every 8 hours.
That’s a wrap!!
If you liked the script and tried it, do let me know via comment.
Follow me if you don’t want to miss my next articles and enhance your knowledge.