The first
( is on the wrong side of the if statement.
You do a superfluous comparison in the first else case: you already know $2 cannot be zero, so why would you test it again?
(While you use the
print and
printf statements correctly, there is a high risk of confusion or error. The former prints all its arguments (similar to
echo in shell scripts), the latter takes a pattern and optional arguments referred to in the pattern. I prefer to put the parameters to
printf in parentheses to emphasize the distinction. Besides, it looks more like the C function then, which is useful, because it works pretty much exactly like the C version.)
You are missing a
} at the end.
Try this approach instead:
If the second field is greater than zero, calculate the percentage (by multiplying the third field by a hundred, then dividing by the second field). Then, print out
p as a percentage. If $2 was zero, then p is unset, and evaluates to zero.
Code:
free -mt | awk '/Swap/ { if ($2 > 0) p = 100.0 * $3 / $2 ; printf("Swap used: %.2f%%\n", p) }'