-1

I am trying to find total size of a current directory and the shell script is failing at expr command. below is my code:

#!/bin/sh
echo "This program summarizes the space size of current directory"

sum=0

for filename in *.sh
do
    fsize=`du -b $filename`
    echo "file name is: $filename Size is:$fsize"
    sum=`expr $sum + $fsize`        
done
echo "Total space of the directory is $sum"
Ravi
  • 163
  • 1
  • 2
  • 12

2 Answers2

1

Try du -b somefile. It will print size and name like this:

263     test.sh

Then you are trying to add both size and name arithmetically to sum which will never work.

You need to either slice away the file name or, better, use stat instead of du:

fsize=`stat -c "%s" $filename`

...and for bash there is a bit cleaner way to do the math which is described here:

sum=$(($sum + $fsize))

output:

This program summarizes the space size of current directory
file name is: t.sh Size is:270
Total space of the directory is 270
fukanchik
  • 2,811
  • 24
  • 29
0

du returns the size and filename, you just want the total size. Try changing your fsize assignment

fsize=$(du -b $filename | awk '{print $1}')

Total size of directory contents, excluding subdirectories and the directory itself:

find . -maxdepth 1 -type f | xargs du -bS | awk '{s+=$1} END {print s}'

du will give actual space used by a directory, so I had to use "find" to really only match files, and awk to add the sizes.

axus
  • 162
  • 1
  • 8
  • Question on your statement "du -b --summarize -S | awk '{print $1}'" – Ravi Jan 26 '17 at 16:59
  • 1
    Question. Below is the output of ls -l -a: 4096 Jan 26 22:06 . 4096 Jan 26 22:06 .. 346 Jan 20 01:26 BreakContinue.sh 805 Jan 17 01:23 DirectorySize.sh 597 Jan 19 02:22 Example1.sh 1245 Jan 13 01:54 fileprocess.sh 325 Jan 12 23:31 first1.sh 477 Jan 14 02:29 LineCount.sh 27 Jan 20 02:44 Outfile.txt 446 Jan 16 20:56 PatternMatch.sh 719 Jan 18 01:54 RetireAge.sh 409 Jan 21 02:01 SizeSum1.sh 420 Jan 26 22:06 SizeSum.sh 142 Jan 13 21:04 sum.sh [edureka@localhost Scripts]$ du -b --summarize -S 10054 . output should have been "5958". why it is 10054? – Ravi Jan 26 '17 at 17:07
  • Yeah that is odd; I ran "find . -maxdepth 1 -type f | xargs du -bS | awk '{s+=$1} END {print s}'" to add up bytes of everything in the current directory, and it came out 12354 bytes smaller than "du -Sb --summarize". Will see if I can figure it out. – axus Jan 26 '17 at 18:25
  • Guessing a bit here, but my using `du` without specifying files is going to include actual space used by the directory itself, in addition to the files. I'm updating my answer... – axus Jan 26 '17 at 18:49