I want to find out total size of some files which filenames may contain whitespaces:

cd /tmp
touch "a0 1"
touch "a1 1"

I put these filenames to variables and make a list:

var0="/tmp/a0 1"
var1="/tmp/a1 1"
var2=`echo -e "$var0\n$var1"`

Now if I check myself and print this list, everything seems OK:

echo "$var2"
#/tmp/a0 1
#/tmp/a1 1

But if I try to get the total size, it somehow misunderstands "\n" symbol

du "$var2"
#du: cannot access ‘/tmp/a0 1\n/tmp/a1 1’: No such file or directory

How do I make du process "\n" as line separator? Or maybe I have to create list in a different way?


I'd suggest using an array instead

var2=( "$var0" "$var1" )

du "${var2[@]}"

See BashGuide/Arrays

  • Actually I guess the full answer would be: du -c "${var2[@]}" | tail -1 or, if OP wants to isolate just a numeric value for reuse in further code, du -c "${var2[@]}" | awk 'END {print $1}'. – Cbhihe Sep 18 '16 at 8:06
  • Unfortunately, I found that if var0 or var1 contains multi-line list of files from the very beginning, this will not work. Thanks for the answer anyways. – Alessandro Cattaneo Oct 2 '16 at 14:30

The solution I found was to split var2 line-by-line in while loop:

var0="/tmp/a0 1"
var1="/tmp/a1 1"
var2="$(echo -e "$var0\n$var1")"

totalsize=0;                                    #this will make script return 0 if var2 somehow contains empty lines only
while read "opened_file"                        #for each file in list do
        if [ ! -z "$opened_file" ]; then        #if variable is not empty
                tmp1="$(du -b "$opened_file" | cut -d"  " -f1)"         #get size of current file and strip unnecessary fields
                totalsize=$(($totalsize + $tmp1))
done <<< "$(echo -e "$var2")"
echo "$totalsize"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.