Reputation: 71
So i'm writing a bash script that has to figure out how much CPU is being used in total according to the command "ps u". I'm trying to use awk like so:
TOTAL_CPU=$(ps u | awk '{sum = sum + $3}; END {print sum}')
Typical output from the command "ps u" has 11 columns, the 3rd being CPU usage.
The problem is, this isn't working like it should. When the CPU value has decimals, I get an error like this:
syntax error: invalid arithmetic operator (error token is ".x")
Where x is the "remaining" decimals after the sum. For example if the values are "1.4" and "8.7", the sum is "10.1", so the error will say:
syntax error: invalid arithmetic operator (error token is ".1")
How can I do what I need? It's ok if the decimal gets truncated, I don't need lots of precision.
EDIT: the post editor changed what I had originally written
EDIT2: Problem solved! It wasn't awk's fault at all; it turns out that this line of code was hiding somewhere else:
declare -i TOTAL_CPU
So bash was trying to assign a value like "3.4" to a variable that was expected to contain integer values only. I'm putting this here in case someone finds this post via google later!
Upvotes: 1
Views: 707
Reputation: 107040
Take a look at the ps
command in the manpage on your system. You can reformat the ps
output to get what you want. For example, you can just print out the CPU amount and forget the rest of the output:
sum=$(ps -udavid -o %cpu | tail -n +2 | paste -sd+ - | bc)
ps -udavid
: Processes owned by davidps -udavid -o %cpu
: Processes owned by david. Just showing the CPUtail -n +2
: Remove the header line (all lines 2 to the end)paste -sd+ -
The -s
means to combine all lines together in a single line. The d+
means put a +
sign after each line. The final -
means use STDIN.bc
calculate the lines. Since all numbers are separated by +
signs, it will add all the CPU amounts together.Upvotes: 2
Reputation: 47269
Change it from:
TOTAL_CPU=ps u | awk '{sum = sum + $3}; END {print sum}'
To:
TOTAL_CPU=$(ps u | awk '{sum = sum + $3}; END {print sum}')
It's not an awk
issue, but rather your bash syntax.
The $(...)
notation is called Command Substitution. Basically, it spawns a new subshell from your current shell to execute whatever command is enclosed by it, and then returns the output to the new subshell's stdout
.
Upvotes: 1