How can I get the size of a file into a variable?
ls -l | grep testing.txt | cut -f6 -d' '
gave the size, but how can I store it in a shell variable?
It would be best to use the stat and other commands under Linux to check the file size. The stat command displays information about the file including its size. Another option is to use the wc command, which can count the number of bytes in each given file.
Using the ls Command –l – displays a list of files and directories in long format and shows the sizes in bytes. –h – scales file sizes and directory sizes into KB, MB, GB, or TB when the file or directory size is larger than 1024 bytes. –s – displays a list of the files and directories and shows the sizes in blocks.
Another method we can use to grab the size of a file in a bash script is the wc command. The wc command returns the number of words, size, and the size of a file in bytes.
Right-click the file and click Properties. The image below shows that you can determine the size of the file or files you have highlighted from in the file properties window. In this example, the chrome. jpg file is 18.5 KB (19,032 bytes), and that the size on disk is 20.0 KB (20,480 bytes).
filesize=$(stat -c '%s' testing.txt)
You can do it this way with ls
(check the man page for the meaning of -s)
var=$(ls -s1 testing.txt | awk '{print $1}')
Or you can use stat
with -c '%s'
.
Or you can use find (GNU):
var=$(find testing.txt -printf "%s")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With