Search code examples
directorysizeexpr

Unix Shell Scripting - expr syntax issue


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"

Solution

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