How to Get File Size in Bytes on Linux and macOS
How can we get a file size in bytes on Linux and macOS?
Suppose we want the file size of file.log.
1. Using stat
stat -c %s file.log # GNU/Linux
stat --format=%s file.log # GNU/Linux
stat -f %z file.log # BSD/macOS
The
statutility executes thelstatsyscall to obtain the file length. It does not read the file, so performance of this command does not depend on the file size.
2. Using ls
We can use ls with the -l flag to view the file metadata in the long list format.
Using -h will append the unit suffix to the file size in bytes: B, K, M, G, T and P.
ls -lh file.log
We can also use awk to print just the file size in bytes.
ls -lh file.log | awk '{print $5}'
Similar to
stat, thelsutility executes thelstatsyscall to obtain the file length. It does not read the file, so performance of this command does not depend on the file size.
3. Using wc
Using wc requires reading through the entire file stream to count the bytes. While being a clean option, it isn’t the best option in regards to speed and resource usage.
It also does not work without read access to the file.
wc -c file.log # Outputs size + filename
wc -c < file.log # Outputs size