Wang Yx
Wang Yx

Reputation: 3

BASH pass a variable to grep produce different result

Script:

echo $1 $n
while true 
do
  ps -aux | awk '{print $1 "\t" $3 "\t" $4 "\t" $11}'  > task.log
  while IFS=' ' read r
  do 
    echo $r
  done < task.log | grep "$n" | awk '/a/{sum+=$1} END{print"Total CPU Usage:", sum}' >> monitor2.log
  sleep $1
done

This is a simple script to see the cpu usage by output -aux result in task.log and let grep and awk process it sum it all by entering a keyword

The problem is that the result is always when I run ./monitor1.sh 2 firefox

Total CPU Usage: 0

I tested if I put grep replace $n with firefox and not variable, the output is

Total CPU Usage: 1.1

Upvotes: 0

Views: 97

Answers (2)

KamilCuk
KamilCuk

Reputation: 140970

In your script:

  • You nowhere assign the variable "$n", thus it is empty. Probably you mean to use n=$2 or just use $2 positional variable instead
  • "task.log" is useless, if you want it use tee to pipe to it
  • Doing ps -axu and then limiting columns with awk looks strange. ps can format the output by itself
  • Parsing ps | grep is bad, use pgrep for that
  • remember to quote the variables

Your script after some fixing may look like this:

while true; do
  cpuusage=$(
      pgrep "$2" | 
      tee >(xargs ps -aux >task.log) | 
      xargs ps -o cpu% |
      awk '{sum += $1} END {print sum}'
  )
  echo "Total CPU Usage: $cpuusage" >> monitor2.log
  sleep "$1"
done
  • pgrep is a better alternative to ps -aux | grep ...
  • xargs passes pgrep outupt to ps -o %cpu=
  • ps -o %cpu= prints percent cpu usage for each process
  • awk is used to sum it.
  • Then a simple echo appends to monitor2.log file.

Upvotes: 1

liborm
liborm

Reputation: 2724

I guess you're after something like this:

ps aux | awk '$11 ~ /firefox/{ sum += $3 } END { print sum }'

The awk checks field 11 of every row produced by ps and if it contains firefox, it executes the associated {} block. Beware, on different systems the ps outputs are different.

You want to run this within a watch command. Eg. like this (notice how you can avoid quoting hell with the use of awk variables).

ps-sum() { ps aux | awk -v regex=$1 '$11 ~ regex { sum += $3 } END { print sum }' ;}
export -f ps-sum

watch -x bash -c "ps-sum firefox"

Upvotes: 0

Related Questions