title: pgrep detect duplicate processes
body: <p>I am trying to use pgrep to first detect if a process is running and if so, determine if the process has been duplicated (run) accidentally. If so, it should it kill the duplicate processes.</p>
  
  <pre><code>if ! pgrep -f "java" &gt; /dev/null; then
    echo "Yes its running but there may be duplicates"
    &lt; Now check for duplicates here and kill if necessary &gt;
  fi
  </code></pre>
  
  <p>Please help</p>
  
  <p><strong>* UPDATE *</strong></p>
  
  <p>ps aux:</p>
  
  <pre><code>debian    2521  3.8  5.4 407212 27524 pts/0    Sl   20:16   0:08 java -cp somefile.jar
  </code></pre>
  
  <p>Code:</p>
  
  <pre><code>if [ $(pgrep -f "somefile.jar" | wc -l) -gt 1 ]; then
    kill $(pgrep -f "somefile.jar" | grep -v $(pgrep -o "somefile.jar") | awk '{printf $1" "}');
  fi
  </code></pre>
  
  <p>Works but throws an error</p>
  
  <p><strong>* UPDATE *</strong></p>
  
  <p>Here is a direct paste of my code:</p>
  
  <pre><code>if [ $(pgrep -f java | wc -l) -gt 1 ]; then
    echo "kill $(pgrep -f java | grep -v $(pgrep -of java) | sort -n | uniq | awk '{printf $1" "}')";
  fi
  </code></pre>