BASH

Find Large Files and Directories

Efficiently locate large files and directories in your file system using bash, helping you manage disk space and identify resource hogs.

#!/bin/bash

TARGET_DIR="." # Or specify a different directory, e.g., "/var/log"

echo "Scanning for large files and directories in: $TARGET_DIR
"

echo "Top 10 largest files (recursive):"
# Find top 10 largest files (recursive) within TARGET_DIR
find "$TARGET_DIR" -type f -print0 | xargs -0 du -h | sort -rh | head -n 10

echo "
Top 10 largest directories (one level deep in TARGET_DIR):"
# Find top 10 largest directories (current directory, one level deep)
du -sh "$TARGET_DIR"/* | sort -rh | head -n 10
How it works: This script provides two common methods for identifying disk space usage. The first command uses `find` to locate all files recursively within a specified directory, pipes their paths to `xargs` and `du -h` to calculate their human-readable sizes, then sorts them by size in reverse order and displays the top 10. The second command uses `du -sh` on all immediate children of the target directory to list their sizes, sorting and displaying the largest 10. This is useful for quickly assessing directory-level usage and identifying where disk space is being consumed.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs