How to Get File Size in Bash: Simple Commands and Examples
In bash, you can get a file's size using the
stat command with -c%s to print the size in bytes, like stat -c%s filename. Alternatively, use wc -c < filename to count bytes, which also returns the file size.Syntax
The main commands to get file size in bash are:
stat -c%s filename: Prints the file size in bytes.wc -c < filename: Counts the number of bytes in the file.
Here, filename is the path to your file.
bash
stat -c%s filename wc -c < filename
Example
This example shows how to get the size of a file named example.txt using both stat and wc. It prints the size in bytes.
bash
echo "Hello World" > example.txt size_stat=$(stat -c%s example.txt) size_wc=$(wc -c < example.txt) echo "Size using stat: $size_stat bytes" echo "Size using wc: $size_wc bytes"
Output
Size using stat: 12 bytes
Size using wc: 12 bytes
Common Pitfalls
Common mistakes when getting file size in bash include:
- Using
wc -c filenamewithout input redirection, which prints the filename along with the size. - Not handling files with spaces or special characters properly.
- Using
statoptions that differ between systems (Linux vs macOS).
For example, on macOS, use stat -f%z filename instead of stat -c%s filename.
bash
wc -c example.txt # Outputs: 12 example.txt wc -c < example.txt # Outputs: 12
Output
12 example.txt
12
Quick Reference
| Command | Description | Example |
|---|---|---|
| stat -c%s filename | Get file size in bytes (Linux) | stat -c%s example.txt |
| stat -f%z filename | Get file size in bytes (macOS) | stat -f%z example.txt |
| wc -c < filename | Count bytes in file | wc -c < example.txt |
Key Takeaways
Use
stat -c%s filename on Linux to get file size in bytes.Use
wc -c < filename to count bytes without printing filename.On macOS, use
stat -f%z filename instead of Linux syntax.Redirect input with
< when using wc -c to avoid extra output.Handle filenames with spaces by quoting or escaping them.