0

I'm writing script in Bash and I have a problem with sum elements of array. I add to array results of df for two paths. In result I want to get sum elements of array.

use=()
i=0
for d in '$PATH1' '$PATH2'
do 
    usagebck=$(du $d | awk '{print awk $1}')
    use[i]=$usagebck
    sum=0
    for j in $use
    do
             sum=$($sum + ${use[$i]})

    done

    i=$((i+1))

done
echo ${use[*]}
5
  • What's your question? Commented Dec 24, 2014 at 14:30
  • Variables do not expand in single quotes. So '$PATH' is the literal string $PATH. Commented Dec 24, 2014 at 14:30
  • There's also no reason to have the usagebck variable in this script as-written. And $use will only give you the first value in the array. Commented Dec 24, 2014 at 14:31
  • So how should be $use ? $use[*] ? Commented Dec 24, 2014 at 14:41
  • Do you actually have a directory name $PATH1, or do you not understand the difference between single quotes and double quotes? You probably meant to write for d in "$PATH1" "$PATH2" Commented Dec 24, 2014 at 16:51

2 Answers 2

3

If your du has option -s:

use=()
sum=0
for d in "$PATH1" "$PATH2"
do
  usagebck="$(du -s "$d" | awk 'END{print $1}')"
  use+=($usagebck)
  ((sum+=$usagebck))
done
echo ${use[*]}
echo $sum
Sign up to request clarification or add additional context in comments.

1 Comment

There's no reason to prefer ${use[*]} over "${use[@]}" here.
1

First, take a look at the parameters in du. On BSD based systems, there's -c which will give you a grand total. On GNU and BSD, there's the -a parameter which will report on all files for a directory.

Since you're already using awk, why not do everything in awk?

$ du -ms $PATH1 $PATH2 | 
  awk 'BEGIN {sum = 0} 
       END {print "Total: " sum } 
       {
           sum+=$1
           print $0
       }'
  • du -ms specifies that I want the total sums of each file specified
  • BEGIN is executed before the main awk program. Here I'm initializing sum. This isn't necessary because variables are assumed to equal zero when created.
  • END is executed after the main awk program. Here, I'm specifying that I want sum printed.
  • Between the { ... } is the main Awk program. Two lines. The first line adds Column 1 (the size of the file) to sum. The second line prints out the entire line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.