0

I need to get swap memory size in bytes from linux so i im executing this command:

{ read firstLine; while read f t s u p; do echo $s; done;} < /proc/swaps

It returns:

523260
523260

And i need to return:

1046520

i try using:

{ read firstLine; while read f t s u p; do echo $s++; done;} < /proc/swaps

but i know that is incorrect of using $s++, i im new to bash so if someone have clue or idea how do i need to increment $s variable with value that is read?

If i have for example:

523260 256523

I need to get output:

779783

John
  • 1,521
  • 3
  • 15
  • 31

2 Answers2

2

If you are looking to sum up the values in the 3rd column, do:

 awk 'NR>1{a+= $3} END {print a}' /proc/swaps

To do the sum your way, you can do:

{ total=0; read firstLine; while read f t s u p; do : $((total += s)); done; echo $total; } < /proc/swaps
William Pursell
  • 204,365
  • 48
  • 270
  • 300
2

In bash, $((expr)) represents the artithmetic evaluation of expr.

A=1
B=2
echo $((A+B))

will print 3.

So you need to first read A and B from /proc/swaps and then add them after they have been assigned.

Note however that this only evaluates integers to integers.

jurez
  • 4,436
  • 2
  • 12
  • 20