Bash shell script for finding file size
Consider:
var=`ls -l | grep TestFile.txt | awk '{print $5}'`
I am able to read file size, but how does it work?
Solution 1:
Don't parse ls
size=$( stat -c '%s' TestFile.txt )
Solution 2:
Yes, so basically you could divide it into 4 parts:
ls -l
List the current directory content (-l
for long listing format)
-
| grep TestFile.txt
Pipe the result and look for the file you are interested in
| awk '{print $5}
Pipe the result to awk program which cuts (by using spaces as separator) the fifth column which happens to be the file size in this case (but this can be broken by spaces in the filename, for example)
- var=`...`
The backquotes (`) enclose commands. The output of the commands gets stored in the var variable.
NOTE: You can get the file size directly by using du -b TestFile.txt
or stat -c %s TestFile.txt