0

I want to get the size of the directory's content. If I use the command line I can get like this:

ls -l | head -n 1 | awk '{ print $2 }'

So the output is the size of the directory's content:

16816

But I want to do this in a bash script:

x="ls -l DBw | head -n 1 | awk '{ print $2 }'"
while sleep 1; do
        y=$(eval "$x");
        echo $y
done

But the output of this script is the full line:

Total 16816

Why is this happening and how can I get just the second word?

al2
  • 119
  • 7
  • It is not recommended to parse `ls` output to commands. If you are looking for directory size for a specific directory then how about simply using `du -h directory_name`? Let us know. – RavinderSingh13 Mar 15 '19 at 01:00
  • Put your command directly inside $() then you don’t get quoting problems from eval. Otherwise you have to quote the $2 I think – eckes Mar 15 '19 at 01:04
  • BTW you can also use the `watch` tool if you only want to see repeating output – eckes Mar 15 '19 at 01:06
  • @RavinderSingh13 I think the total from ls does not include subdirectories but from du it does – jhnc Mar 15 '19 at 01:08
  • Another problem here is with regard to block size. A 1 byte file is only 1 byte long, but it uses a *block* on the disk, and that block is of an unknown size. The `du` command will add up **D**isk **U**sed, i.e. blocks, whereas the output of `ls` might better reflect the eventual size of an uncompressed `tar` file. @al2, it would be great if you could share what you're trying to achieve here, so that we can recommend a more appropriate alternative. – ghoti Mar 15 '19 at 01:54
  • Related: [How do I set a variable to the output of a command in Bash?](/q/4651437/4518341) – wjandrea Jul 13 '22 at 18:04

1 Answers1

2
x="ls -l DBw | head -n 1 | awk '{ print $2 }'"

It's happening because $2 is inside double quotes and so it's interpreted immediately. You could escape it with \$2, but better yet:

Don't store code in variables. Use a function.

x() {
    ls -l DBw | head -n 1 | awk '{ print $2 }'
}

Then you can call x many times.

while sleep 1; do
    x
done

That said, it's better not to parse the output of ls in the first place. Use du to compute the size of a directory:

$ du -sh /dir
1.3M   /dir
$ du -sh /dir | cut -f1
1.3M
John Kugelman
  • 349,597
  • 67
  • 533
  • 578