I need help for the following problem: I'd like to kill all instances of a program, let's say xpdf. At the prompt the following works as intended:
$ ps -e | grep xpdf | sed -n -e "s/^[^0-9]*\([0-9]*\)[^0-9]\{1,\}.*$/\1/p" | xargs kill -SIGTERM
(the sed-step is required to extract the PID).
However, there might be the case that no xpdf-process is running. Then it would be difficult, to embed the line into a script, because it aborts after it immediately with a message from kill. What can I do about it?
I tried (in a script)
#!/bin/bash
#
set -x
test=""
echo "test = < $test >"
test=`ps -e | grep xpdf | sed -n -e "s/^[^0-9]*\([0-9]*\)[^0-9]\{1,\}.*$/\1/p"`
echo "test = < $test >"
if [ -z "$test" ]; then echo "xpdf läuft nicht";
else echo "$test" | xargs -d" " kill -SIGTERM
fi
When running the script above I get
$ Kill_ps
+ test=
+ echo 'test = < >'
test = < >
++ ps -e
++ grep xpdf
++ sed -n -e 's/^[^0-9]*\([0-9]*\)[^0-9]\{1,\}.*$/\1/p'
+ test='21538
24654
24804
24805'
+ echo 'test = < 21538
24654
24804
24805 >'
test = < 21538
24654
24804
24805 >
+ '[' -z '21538
24654
24804
24805' ']'
+ xargs '-d ' kill -SIGTERM
+ echo '21538
24654
24804
24805'
kill: failed to parse argument: '21538
24654
24804
24805
Some unexpected happens: In test there are more PIDs then processes
At the prompt:
$ ps -e | grep xpd
21538 pts/3 00:00:00 xpdf.real
24654 pts/2 00:00:00 xpdf.real
When running the script again, the 24* PIDs change.
So here are my questions:
- Where do the additional PIDs come from?
- What can I do to handle the situation, in which no process I want to kill is running (or why does xargs not accept
echo "$test"
as input)? (I want my script not to be aborted)
Thanks in advance.