Bash – Get file size
To get file size in Bash scripting, we can use wc
command as shown in the following.
</>
Copy
wc -c <"$filename"
wc command with -c option prints the byte counts for the file.
Example
In the following script, we take a file at path "sample.txt"
in filename
. We check if the file exists, and if so, get the number of bytes present in file using wc
command.
sample.txt – File contents
example.sh
</>
Copy
#!/bin/bash
filename="sample.txt"
# Check if the file exists
if [ -f "$filename" ]; then
# Get the length of the file
filesize=$(wc -c <"$filename")
echo "Number of bytes in file is: $filesize"
else
echo "Given file does not exist."
fi
Bash Version: GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin22.1.0)
Output
sh-3.2# bash example.sh
Number of bytes in file is: 42
References
Conclusion
In this Bash Tutorial, we learned how to append text to file using echo command.