rafc rafc - 1 year ago 79
Linux Question

awk script always prints sum=0

I'm sorry if the question might be silly, but I am totally new to awk scripting.
What I want to do is to calculate and print the usage of CPU and memory by the user "root".
I wrote this bash script which executes an awk script:


ps aux > processi.txt
echo Lancio script3.awk
awk -f script3.awk processi.txt

and the awk script is the following:


print "Inizio script\n"

printf("Cpu usata da root loop=%.1f, memoria=%.1f\n",$3,$4)


printf("Cpu usata da root=%.1f, memoria=%.1f\n",$cpu,$mem)
print "\nFine script\n"

But the print from the END is 0, while in /root/ is correct.
Any advice?

Answer Source

The $ isn't used to expand variables in awk, where it signals the expansion of a particular input field whose number is contained in the given variable. That is, if cpu=3, then $cpu is equivalent to $3. Just use the variable name by itself.

  printf("Cpu usata da root=%.1f, memoria=%.1f\n", cpu, mem)
  print "\nFine script\n"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download