I have a line in a script combing out how much memory a certain user takes:
ram=`ps -u $ID --no-headers -o rss`

The ram variable gets:
echo $ram
29448
18128
61672
29116
35376

How can I add these numbers more correctly?
  • Type"bash math" or"bash sum" on Google.
    Follow at least the first pair of links.
    – Combat20 Aug 21 '19 at 10:29

3 Answers 3

ram=`ps -u $ID --no-headers -o rss | awk'{sum +=$1} END {print sum}'`
echo $ram
  • I did not expect that you can do this with awk, I also found this option:
    paste -sd + $ram | bc
    – Brainy23 Aug 21 '19 at 10:54
echo"$(ps h -u $ID -o rss | tr'\ n''+'| tr -d'') 0" | bc


But I believe that the solution via awk from[[Skyrimus]] is more clear.

You can generally
echo"$(($(ps h -u $ID -o rss | tr'\ n''+'| tr -d'') 0))"
  • Since I do not know awk, then your option is clearer to me :) – Brainy23 Aug 21 '19 at 13:55
  • Ah, well then you can even without bc
    just $((a + b + c + d))

    echo"$(($(ps h -u $ID -o rss | tr'\ n''+'| tr -d'') 0))"
    – Gifted Grebe Aug 21 '19 at 16:47
sum=$(($num1 + $num2))
echo $sum
  • This is understandable, I need to calculate the sum of the numbers in one variable.It comes to mind to put these numbers in an array, then cycle through it and add it.But there may be an easier way, maybe there is a ready-made utility. – Brainy23 Aug 21 '19 at 10:35
  • [[semenenko88]],
    It comes to mind to put these numbers into an array, then cycle through it and add it.

    This.
    Well, a ready-made utility for finding the sum of the elements of an array is glum.
    – Annoying Antelope Aug 21 '19 at 10:37
  • man awk – Dizzy54 Aug 21 '19 at 10:46
  • you can without a loop, just delete extra characters =)
    tweaked a little variant with
    $(())
    – Gifted Grebe Aug 21 '19 at 16:48