2

Consider:

var=`ls -l | grep TestFile.txt | awk '{print $5}'`

I am able to read file size, but how does it work?

3
  • var=ls -l | grep TestFile.txt | awk '{print $5}' reverse quote is not visible here, when i check -> ls -l | grep TestFile.txt output is only file is displayed how come awk got the size also Commented Oct 1, 2015 at 14:55
  • Just as a side note, this seems like an awfully long-winded way to write du. Commented Oct 1, 2015 at 15:07
  • stat -c %s TestFile.txt would be a far superior approach... Commented Oct 1, 2015 at 15:44

2 Answers 2

4

Don't parse ls

size=$( stat -c '%s' TestFile.txt )
Sign up to request clarification or add additional context in comments.

2 Comments

Another one of those "use the proper tool for the job" scenarios... ls - list files, stat - file statistics. Clever names...
The link is broken ("400 Bad Request"). Perhaps add the why inline?
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

5 Comments

Thanks i read in stack overflow and used du however it byte read b is not supported my board # du -b du: invalid option -- 'b' BusyBox v1.20.2 (2015-09-29 11:55:16 IST) multi-call binary. Usage: du [-aHLdclsxk] [FILE]...
@Dam if redobot's answer indeed helped you, make sure to accept it (tick it as correct).
@Dam it seems that BusyBox's version of du doesn't support showing the file size in bytes. Leave the -b option off (or substitute with -k) and it'll show file sizes in kilobytes instead.
looks like the BusyBox version is different from the GNU's version. unix.stackexchange.com/questions/157817/…. As @IanMcLaird said you could use the other options (-k, -m or -h). This should be OK unless you would like to use the size in some mathematical operation.
@redobot Also note that du and stat can report two very different numbers in the case of sparse files - stat will report the same number that ls -l does, which is why it is probably the better answer in this case, while du will report the actual total disk space actually being used (although some versions of du have an --apparent-size or similar option).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.