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:

  1. ls -l

List the current directory content (-l for long listing format)

  1. | grep TestFile.txt

Pipe the result and look for the file you are interested in

  1. | 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)

  1. 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