When trying to check file sizes in a directory using du -hm
, many users encounter the error:
du: cannot access -': No such file or directory
This typically happens when piping commands incorrectly. The xargs
approach shown in the example won't work because du
expects file paths, not piped output in that format.
To properly check file sizes in megabytes:
du -hm /usr/local/apache2/logs/*
This will show each file's size in MB format. The -h
makes it human-readable, while -m
forces MB units.
For more detailed analysis, consider these variants:
# Show sizes sorted by largest files first
du -hm /usr/local/apache2/logs/* | sort -nr
# Show only files larger than 10MB
du -hm /usr/local/apache2/logs/* | awk '$1 > 10'
# Summarize directory totals
du -hm --max-depth=1 /usr/local/apache2/logs/
When dealing with spaces in filenames or many files:
# Handle spaces in filenames
find /usr/local/apache2/logs/ -type f -exec du -hm {} +
# For directories with thousands of files
find /usr/local/apache2/logs/ -type f | xargs du -hm
For very large directories, find
with -exec
will be more reliable than shell expansion with *
. The +
terminator for -exec
is more efficient than \;
as it passes multiple files to du
at once.
Many Linux users try to check file sizes with commands like:
ll /usr/local/apache2/logs/ | xargs | du -hm -
du: cannot access -': No such file or directory
This fails because du
doesn't process piped input in the expected way.
To see sizes of all files in a directory in megabytes:
du -hm /usr/local/apache2/logs/*
This will display each file's size in MB format with a full path.
Using find with du
For more control, combine find
with du
:
find /usr/local/apache2/logs/ -type f -exec du -hm {} \;
Sorting by File Size
Add sort to identify largest files:
du -hm /usr/local/apache2/logs/* | sort -nr
Including Hidden Files
The basic wildcard (*) won't catch hidden files. To include them:
du -hm /usr/local/apache2/logs/.* /usr/local/apache2/logs/*
Checking Log File Sizes
du -hm /var/log/*.log | sort -nr | head -10
Monitoring Specific File Types
du -hm /home/user/Downloads/*.iso
For directories with thousands of files, these alternatives are faster:
ls -lhS /path/to/dir | head -20 # Human-readable sorted listing
find /path/to/dir -type f -printf "%s %p\n" | sort -nr | head -20