Bash – Get file size
To get file size in Bash scripting, we can use
wc command as shown in the following.
wc -c <"$filename"
wc command with -c option prints the byte counts for the file.
In the following script, we take a file at path
filename. We check if the file exists, and if so, get the number of bytes present in file using
sample.txt – File contents
#!/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)
sh-3.2# bash example.sh Number of bytes in file is: 42
In this Bash Tutorial, we learned how to append text to file using echo command.