title: Count the number of processes and kill them
body: <p>I am writing a script to kill all instances of the same process. As it is going to be used on Linux, AIX, HP-UX and Solaris, I need to use only built-in bash (sh) functions. That's why <code>killall</code>, <code>pkill</code>, etc. don't work for me.</p>
  
  <p>Once there is only one instance of a process it should be just killed in traditional way:  </p>
  
  <pre><code>kill -TERM `ps -ef | grep -v grep | grep $process | awk '{print $2}'`
  </code></pre>
  
  <p>However sometimes the program has extra instances running and that's why <code>ps -ef | …</code> returns more than one PID. That needs to be reported.</p>
  
  <p>example:  </p>
  
  <pre><code>bash-3.2$ ps -ef | grep -v grep | grep perl | awk '{print $2}'
  5267  
  5268  
  5269  
  5270  
  5271
  </code></pre>
  
  <p>My thought was to store those values in a temporary variable and then send kill signal to each in a for loop.</p>
  
  <pre><code>bash-3.2$ tmp=`ps -ef | grep -v grep | grep perl | awk '{print $2}'`  
  bash-3.2$ echo $tmp  
  5267 5268 5269 5270 5271
  </code></pre>
  
  <p>However I still need the information if such a case occurred (how many instances were present).
  It seems I need to check the whole string stored in the <code>tmp</code> variable and maybe count spaces? </p>
  
  <p>Anyway the questions reduces to how to check how many values the <code>$tmp</code> variable stores? </p>