Bash Script to Find Largest File in Directory
ls -S | head -n 1 to list files sorted by size and pick the largest, or use find . -type f -exec ls -s {} + | sort -n -r | head -n 1 for a more robust script.Examples
How to Think About It
Algorithm
Code
#!/bin/bash largest_file=$(find . -maxdepth 1 -type f -exec ls -s {} + | sort -n -r | head -n 1 | awk '{print $2}') echo "$largest_file"
Dry Run
Let's trace a directory with files file1.txt (100 bytes), file2.txt (200 bytes), file3.txt (50 bytes) through the code
Find files and list sizes
find . -maxdepth 1 -type f -exec ls -s {} + outputs: 200 ./file2.txt 100 ./file1.txt 50 ./file3.txt
Sort by size descending
Sorted output: 200 ./file2.txt 100 ./file1.txt 50 ./file3.txt
Select largest file
head -n 1 picks: 200 ./file2.txt awk '{print $2}' extracts: ./file2.txt
| Size | File |
|---|---|
| 200 | ./file2.txt |
| 100 | ./file1.txt |
| 50 | ./file3.txt |
Why This Works
Step 1: Find files with sizes
The find command locates files and ls -s lists their sizes in blocks.
Step 2: Sort files by size
Sorting numerically in reverse order with sort -n -r puts the largest file first.
Step 3: Extract largest file name
Using head -n 1 picks the top file, and awk '{print $2}' extracts its name.
Alternative Approaches
largest_file=$(ls -S | head -n 1) echo "$largest_file"
largest_file=$(find . -maxdepth 1 -type f -printf '%s %p\n' | sort -nr | head -n 1 | cut -d' ' -f2-) echo "$largest_file"
Complexity: O(n log n) time, O(n) space
Time Complexity
Listing and sorting all files takes O(n log n) time, where n is the number of files.
Space Complexity
The script stores file info temporarily, using O(n) space for sorting.
Which Approach is Fastest?
Using ls -S is fastest but less reliable; find with stat is more robust but slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| ls -S | head -n 1 | O(n log n) | O(n) | Simple cases, no spaces in filenames |
| find . -exec ls -s {} + | sort -n -r | head -n 1 | O(n log n) | O(n) | General use, handles spaces |
| find . -printf '%s %p\n' | sort -nr | head -n 1 | O(n log n) | O(n) | Precise size, handles spaces well |
find with sort for reliable results even with complex filenames.ls alone without sorting by size or handling spaces in filenames can give wrong results.