Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to do:

Fing the pid of process based on something I grep for, lets say "Name":

pid=(ps aux | grep '[Ń]ame' | awk '{print $2}' | head -1)

Then kill it

kill $pid

This works fine if I log into the machine with ssh, but I want to do it from a script. And it doesn't work then:

ssh hostname "pid=\$(ps aux | grep '[N]ame' | awk '{print $2}' | head -1); echo \$pid"
root 11203 1.5 0.8 6961292 135420 pts/0 Sl 16:52 0:04 java -XX:PermSize=256m -XX:MaxPermSize=512m -Dproperties....

I would like to know a way of doing this and why the results are different when doing the command as in the latter case.

share|improve this question
up vote 1 down vote accepted

You can use pgrep to simplify the search and pipe the result with xargs to remove the use of vars, like:

ssh hostname "pgrep emacs | head -1 | xargs echo"

Your main problem is that bash try to evaluate $2 in the ssh command. It results to a blank, so interprets that you want to pipe `awk '{print }' instead. You can also try to execute with another escape character:

ssh hostname "pid=\$(ps aux | grep '[N]ame' | awk '{print \$2}' | head -1); echo \$pid"

That version works.

share|improve this answer

killall has a -r option to match process name on a regular expression.

-r, --regexp Interpret process name pattern as an extended regular expression.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.