0

I need to find process by string matching, and the kill it, need to do it in one line in another script file: here's what I tried:

'kill $(ps -ef|grep xxx|grep -v grep | awk '{print $2 }' )'
"kill $(ps -ef|grep xxx|grep -v grep | awk '{print $2 }' )"

first one didn't work because of the nested single quote, second one didn't work because $2 is taken by the parent script to be argument 2 to parent script. how do I do this?

user121196
  • 30,032
  • 57
  • 148
  • 198

1 Answers1

3

The easiest way to accomplish that task is:

pkill xxx

(which you'll find in the debian/ubuntu world in package procps, if you don't have it installed.) You might need to use pkill -f xxx, depending on whether xxx is part of the process name or an argument, which is often the case with script execution.

However, to answer the more general question about shell-quoting, if you need to pass the string

kill $(ps aux | grep xxx | grep -v grep | awk '{print $2}')

as an argument, you need to use backslash escapes:

bash -c "kill \$(ps aux | grep xxx | grep -v grep | awk '{print \$2}')"

Or, you can paste together several quoted strings:

bash -c 'kill $(ps aux | grep xxx | grep -v grep | awk '"'"'{print $2}'"'"')'

Personally, I find the first one more readable but YMMV.

You can only backslash escape a few characters inside a double-quoted string: $, ", \, newline and backtick; and inside a single-quoted string backslash is just backslash. However, that's enough to let you type just about anything.

rici
  • 234,347
  • 28
  • 237
  • 341