When managing an Ubuntu Server, disk space can quickly become an issue, especially if large files accumulate unnoticed. If you need to identify the biggest file within a directory (including subdirectories), Linux provides several powerful command-line tools to help.
In this guide, we’ll explore different methods to find the largest file in a directory recursively, making it easy for even beginners to follow along.
Step 1: Open the Terminal Application
- First, you need to open a terminal on your Ubuntu Server. If you are connected via SSH, simply log in to your server.
Step 2: Switch to Root User
- For full access, switch to the root user by running:
sudo -i
- Enter your password if prompted.
Method 1: Using the du Command with Sorting
- A simple and effective way to find the largest files is to use the du command in combination with sort and head.
du -a /path/to/directory/ | sort -n -r | head -n 20
Explanation:
- du -a /path/to/directory/ → Estimates file space usage for all files and directories.
- sort -n -r → Sorts files numerically (-n) in reverse order (-r), showing the largest files first.
- head -n 20 → Displays the top 20 largest files.
Method 2: Using the find Command
- The find command is a powerful tool for locating files based on size, modification time, and other attributes. To find the largest file in a directory recursively, use:
find /path/to/directory -type f -exec du -h {} + | sort -rh | head -n 1
Explanation:
- find /path/to/directory -type f → Searches for all files in the specified directory and its subdirectories.
- -exec du -h {} + → Uses the du (disk usage) command to display the sizes of files in a human-readable format.
- sort -rh → Sorts the files in descending order based on size (-r for reverse order, -h for human-readable sorting).
- head -n 1 → Displays the first (largest) file.
Method 3: Using ncdu for an Interactive View
- If you prefer a user-friendly and interactive approach, install and use ncdu:
sudo apt install ncdu -y ncdu /path/to/directory
Explanation:
- ncdu scans the directory and presents an interactive interface where you can navigate and identify large files easily.
Bonus: Finding and Deleting Large Files
- If you need to find and remove large files, use:
find /path/to/directory -type f -size +500M -exec rm -i {} \;
- This will locate all files larger than 500MB and prompt you before deletion.
Conclusion:
By using du, find, and ncdu, you can quickly locate large files that may be consuming valuable disk space on your Ubuntu Server. These methods ensure efficient disk space management and keep your server running smoothly.
For more Linux and server management support, visit our Hosting and Server Admin Service.
Disclaimer: Portions of this content were enhanced with the assistance of ChatGPT.