2

Here is what I have in my shell file:

FILENAME=/var/lib/backups/html-backup/backup-15-04-2016.tar.gz;
FILESIZE= $(ls -lah $FILENAME | awk '{ $FILESIZEINGB = $5}')
echo "Size is $FILESIZEINGB ."

Can you please tell me why I can not see the file size in readable form ?

It seems $FILESIZEINGB is not set and I can not see the result in the echo output.

3 Answers 3

5

You cannot set a shell variable from a child process - so setting FILESIZEINGB wouldn't work anyway (and it wouldn't work because that means something else in awk syntax).

Just use du -h:

FILESIZEINGB=$(du -h "$FILENAME" | awk '{print $1}')

Also:

  • You shouldn't have a space after =.
1
  • 1
    Technically du -h --apparent-size "$FILENAME" would be the correct way to emulate ls -lah "$FILENAME", otherwise you get the real size.
    – kos
    Apr 15, 2016 at 16:26
2

Or if you don't want to use du:

FILESIZE=$(ls -lah $FILENAME | awk '{ print $5}')
echo "Filesize is $FILESIZE"
1
  • 1
    You can simplify it by just using ls -sh - and the awk command becomes the same as mine.,
    – muru
    Apr 15, 2016 at 16:32
2

I found someone made an AWK one-liner, and it had a bug but I fixed it. I also added in petabytes after terabytes.

FILE_SIZE=234234 # FILESIZE IN BYTES
FILE_SIZE=$(echo "${FILE_SIZE}" | awk '{ split( "B KB MB GB TB PB" , v ); s=1; while( $1>1024 ){ $1/=1024; s++ } printf "%.2f %s", $1, v[s] }')

Considering stat is not on every single system, I would use the AWK solution. Example; the Raspberry Pi does not have stat but it does have awk.

1
  • 3
    You mentioned that you found this and fixed a bug, but where did you find it, and what did you fix?
    – wjandrea
    Jul 3, 2017 at 1:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .