Shell script to kill a process
12,152
to check if a process is running on mac os x you can use:
pid=$(ps -fe | grep 'process name' | grep -v grep | awk '{print $2}')
if you want to reduce the number of shell scripts you can enclose one of the characters of the name of the process in square brackets:
pid=$(ps -fe | grep '[p]rocess name' | awk '{print $2}')
combined in your test this would look like:
pid=$(ps -fe | grep '[p]rocess name' | awk '{print $2}')
if [[ -n $pid ]]; then
kill $pid
else
echo "Does not exist"
fi
it's a little more complicated than you would need to do under linux as you generally have the 'pgrep' command, which is the rough equivalent of the 'ps -fe | grep ... | grep -v grep'
Author by
Ana
Updated on June 04, 2022Comments
-
Ana almost 2 years
I need to implement a shell script that kills a process. The problem is that I need to do a conditional to be able to see if the process is running or not.
This is my code, but it is not working:
#!/bin/sh if [ -x "MY_PROCCESS_NAME"]; then killall MY_PROCCESS_NAME else echo "Doesn't exist" fi
This is the error:
line 3: [: missing `]'
-
Shawn Chin over 12 yearsIf you're going to use
awk
anyway, skip the grep --awk '/[p]rocess_name/{print $1}'
-
Ana over 12 yearsThanks for the answer!. When I run your code, I am always obtaining the "Does not exist" message, even if the process is running.
-
Anya Shenanigans over 12 yearsSounds like the pattern match is not finding your process. Make sure that "ps -fe | grep '[p]rocess name'" gives you a line matching the process, so for example if you were looking for WindowServer then the line would read "ps -fe | grep '[W]indowServer'"
-
Ana over 12 yearsI had an issue with the script, now is fine, but when I run the script, it kills all my machine :S, I only see the desktop image, the other programs and process disapear.
-
Anya Shenanigans over 12 yearsIt's the usual problem of making sure that you only match your process, and not anything else - e.g. If your program is called 'inder' then the Greg of the process will also pick up on 'Finder', which would kill your desktop!
-
Ana over 12 yearsI changed the first line for this an it worked!pid=$(ps -ef | awk '/[p]rocess name/{print $2}')
-
Matt Wielbut about 11 yearsThis doesn't work - the first column running ps -fe is the UID, not the PID (the second column). You should end the command with
awk '{print $2}'
- note the 2