-1

In shell script in centos, i write following 2 lines

cmdread="Myprogram"
kill -9 `ps ax | grep $cmdread `

But some times when manually myprogram stopped then my shell script give me warning that nothing to kill. So how to check like following

if(by grep myprogram's pid != null){
kill it
}
Mandar Khire
  • 13
  • 1
  • 5

2 Answers2

2

For your purpose, you must pass your program's PID to kill command, something like this:

cmdread="Myprogram"
_PID=`ps ax | grep $cmdread | grep -v grep | awk '{print$1}'`

if [[ "x$_PID" != "x" ]]
then
    kill -9 $_PID
fi

UPDATE

I add grep -v grep to my code, although without it, my code will run ok because we can pass multiple PID to kill command.

cuonglm
  • 2,386
  • 2
  • 16
  • 20
-2

For a safer process management I would use the proper reserved variable $! or pgrep if you have it on CentOS.

E,g

#!/bin/sh
cmdread=$(myprogram)
mypid=$!

kill -0 $mypid && printf '%s\n' "My process is stil alive"
kill $mypid

Using pgrep kill $(pgrep programname)

Using grep if ps -ef | grep '[p]rogramname' | grep -q programname; then pkill programname; fi

Please see the following link http://mywiki.wooledge.org/ProcessManagement for a better understanding about Process Management.

Valentin Bajrami
  • 4,045
  • 1
  • 18
  • 26
  • Wrong way. `$!` refer to PID of last background process ID. – cuonglm Jul 23 '13 at 09:15
  • Sure that's why I provided a few options. The first one is to show how you can get the process id of the program you just ran and store it in a variable. You then can decide what to do with it. Your use of back-ticks is Wrong though. – Valentin Bajrami Jul 23 '13 at 09:24
  • Your way to get the process id of the program is wrong. Remember, `$!` is the PID of last background process. Thinking what is background process? And I don't think using back-ticks is wrong. Do you try my code? – cuonglm Jul 23 '13 at 09:39
  • @Gnouc I don't want to argue with you. I know many people who stick with their conservative ideas and they think !sh or bash has not developed through past years. Your code has a lot of flaws. Using awk in this case is pretty much useless since you are invoking another process without a reason. See http://mywiki.wooledge.org/Quotes?highlight=%28back%29|%28ticks%29 about back-ticks. – Valentin Bajrami Jul 23 '13 at 10:01