rafc
rafc

Reputation: 78

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:

#!/bin/bash

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

and the awk script is the following:

#!/usr/bin/awk

BEGIN{
print "Inizio script\n"
cpu=0
mem=0
}

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

        cpu=cpu+$3
        mem=mem+$4
}

END{
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?

Upvotes: 3

Views: 349

Answers (3)

chicks
chicks

Reputation: 2463

While this doesn't address your question per se, an additional suggestion that won't fit in a comment is: formatting your code consistently will make your code easier to read and debug.

Like so:

#!/usr/bin/awk

BEGIN {
    print "Inizio script\n"
    cpu = 0
    mem = 0
}

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

    cpu = cpu + $3
    mem = mem + $4
}

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

where I

  • indented anything inside {} to the same level
  • put spaces around operators like = and +
  • put spaces between the block labels and the opening {
  • put spaces after ,s in your printf() arguments
  • also removed the extraneous $ mentioned in the other answer.

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The initial approach seems to be redundant. Use can extract the needed fields for the user name root directly by ps options:

The whole job:

ps U root -eo  %cpu,%mem --no-header | awk 'BEGIN{ print "Inizio script\n" }
    { printf("Cpu usata da root loop=%.1f, memoria=%.1f\n",$1,$2); cpu+=$1; mem+=$2; }
    END { printf("Cpu usata da root=%.1f, memoria=%.1f\n\nFine script\n", cpu, mem) }'

  • U root - select data only for the user name root

  • -eo %cpu,%mem - output only cpu and mem field values

Upvotes: 2

chepner
chepner

Reputation: 530922

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.

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

Upvotes: 4

Related Questions