title: Linux - Extract core utilization for a single process to a file
body: <p>I am trying to figure out how to extract the cpu core utilization for a SINGLE process in linux and parse it. I know that I can get the overall core utilization via top and then press "1". I am already able to parse that. However, now I want to do the same thing for a single process. I tried it with ps and calculating the core utilization myself but I am not so sure if my script is accurate enough, something seems off. (Note that this version calculates overall core utilization since it is WIP) I get errors like this after a while in my terminal: </p>
  
  <blockquote>
    <p>test.sh: line 31: +: syntax error: operand expected (error token is
    "+")</p>
  </blockquote>
  
  <p>I cannot figure out why this error just randomly occurs.</p>
  
  <pre><code>#!/bin/env bash
  read -p "Enter PID to observe:" pid
  run=false
  ps -p $pid -L -o cputime,etime,psr,pcpu
  
  for (( u = 1 ; u &lt;= 100 ; u++ ))
  do
  
  lines=$(ps -p $pid -L -o psr,pcpu | awk 'END{print NR}')
  
  
      for (( i=1; i&lt;=$lines; i++))
      do
  
  
          core=$(ps -p $pid -L -o psr,pcpu | awk 'NR=='$i'{print $1}')
  
          if [ $run == false ]
  
              then cpuTimeS=+$(ps -p $pid -L -o cputime,etime | awk 'NR=='$i'{print $1}' | awk -F : '{ printf("%.2f\n", $1*60+$2*60+$3); }')
              elapsedTimeS=+$(ps -p $pid -L -o cputime,etime | awk 'NR=='$i'{print $2}' | awk -F : '{ printf("%.2f\n", $1*60+$2*60+$3); }')
  
              cpuTimeSi=${cpuTimeS%.*}        
              elapsedTimeSi=${elapsedTimeS%.*}
  
              cpuTimeSiResult=$(( cpuTimeSi + cpuTimeSiResult ))
              elapsedTimeSiResult=$(( elapsedTimeSi + elapsedTimeSiResult ))
  
              else
              cpuTimeE=+$(ps -p $pid -L -o cputime,etime | awk 'NR=='$i'{print $1}' | awk -F : '{ printf("%.2f\n", $1*60+$2*60+$3); }')
              elapsedTimeE=+$(ps -p $pid -L -o cputime,etime | awk 'NR=='$i'{print $2}' | awk -F : '{ printf("%.2f\n", $1*60+$2*60+$3); }')
  
              cpuTimeEi=${cpuTimeE%.*}        
              elapsedTimeEi=${elapsedTimeE%.*}
  
              cpuTimeEiResult=$(( cpuTimeEi + cpuTimeEiResult ))
              elapsedTimeEiResult=$(( elapsedTimeEi + elapsedTimeEiResult ))
  
          fi  
  done
  
  if [ "$run" = true ]
  
          then result=$( echo "scale=2; ($cpuTimeEiResult - $cpuTimeSiResult) / ($elapsedTimeEiResult - $elapsedTimeSiResult) * 100.0" | bc)
          echo "RESULT:" $result
          echo "cpuTimeSTART:" $cpuTimeSiResult
          echo "elapsedTimeSTART:" $elapsedTimeSiResult
          echo "cpuTimeEND:" $cpuTimeEiResult
          echo "elapsedTimeEND:" $elapsedTimeEiResult
  
  fi
  
  sleep 1
  
  if [ "$run" = false ]
      then run=true
  else
      run=false
  fi
  
  
  
  done
  </code></pre>
  
  <p>Are there any ideas on how I could solve this better?</p>
  
  <p>I am glad for any advice</p>