how can I kill a process in a shell script - linux

My bash script has:
ps aux | grep foo.jar | grep -v grep | awk '{print $2}' | xargs kill
However, I get the following when running:
usage: kill [ -s signal | -p ] [ -a ] pid ...
kill -l [ signal ]
Any ideas, how to fix this line?

In general, your command is correct. If a foo.jar process is running, its PID will be passed to kill and (should) terminate.
Since you're getting kill's usage as output, it means you're actually calling kill with no arguments (try just running kill on its own, you'll see the same message). That means that there's no output in the pipeline actually reaching xargs, which in turn means foo.jar is not running.
Try running ps aux | grep foo.jar | grep -v grep and see if you're actually seeing results.

As much as you may enjoy a half dozen pipes in your commands, you may want to look at the pkill command!
DESCRIPTION
The pkill command searches the process table on the running system and signals all processes that match the criteria
given on the command line.
i.e.
pkill foo.jar

Untested and a guess at best (be careful)
kill -9 $(ps -aux | grep foo.jar | grep -v grep | awk '{print $2}')
I re-iterate UNTESTED as I'm not at work and have no access to putty or Unix.
My theory is to send the kill -9 command and get the process id from a sub shell command call.

Related

Why does my kill .sh script sometimes not kill the intended processes?

I have a .sh script that calls a number of other .sh scripts and tee's them into log files, and runs them in the background:
startMyProg.sh:
#!/bin/bash
./MyProg1.sh | tee /path/to/log/prog1_`date +\%Y\%m\%d_\%H\%M\%S`.log &
./MyProg2.sh | tee /path/to/log/prog2_`date +\%Y\%m\%d_\%H\%M\%S`.log &
./MyProgN.sh | tee /path/to/log/progN_`date +\%Y\%m\%d_\%H\%M\%S`.log &
I also have a simple helper script that will kill all the processes with MyProg in the name:
killMyProgs.sh:
#!/bin/bash
kill $(ps aux | grep MyProg | awk '{print $2}')
This system generally works, but occasionally the killMyProg.sh script doesn't kill the processes that it finds using the ps|grep|awk pattern. The part that really throws me for a loop is, when I face an instance where the .sh script doesn't kill the processes, I can call kill $(ps aux | grep MyProg | awk '{print $2}') directly from the command line and it will do what I expect it to! Is there something that I'm missing in my approach? Are there any useful debugging techniques that can help me figure out why my .sh script doesn't kill the processes but calling the exact command from the command line does?
A couple of details that may be relevant:
the "./MyProgN" scripts are calls to to start the same MyProg.jar file with different inputs. So the ps|grep of "MyProg" shows both the .sh scripts AND the java applications that they started and kills all of them.
Using RHEL7
Test few time to run:
ps aux | grep MyProg | awk '{print $2}'
You will notice that sometimes the grep command comes before MyProg
And sometimes grep command comes after MyProg (depnding on the pid).
Because grep command is listed as well in ps aux.
Therefore sometimes your script is killing the first grep command instead of your command.
The easiest solution is to use pkill command.
pkill -9 -f MyProg

how to use kill command only with files name without PID

I wanna kill programs with one command
ps -elf | grep "common_program_name" | grep -v grep | awk '{print $2}' | xargs kill -9
but I got an error
kill: failed to parse argument: 'S
what am I doing wrong ?
Use killall -9 common_program_name
the problem above is that you might have more than one instance of the program running.
Also, you are fetching the second column from the output of ps That column does not contain a PID, so your xargs command effectively runs kill -9 S Perhaps you can adjust your flags to ps or your field captured by awk to make the above work, but there are already purpose built programs which do this job.
Use pkill, in your case pkill -9 common_program_name (for more see man pkill) which gives you the functionality you're looking for. And unlike killall won't kill literally all process on System V UNIX machines. ;)

grepping the PID of a process - Unix

I'm trying to execute the following command:
ps aux | grep com.scheduler.app.workermain | kill -15 [pid]
How can I obtain the [pid] (or list of PID) using ps aux | grep "expression" and pipe that to kill? There may be zero or many processes running the machine. This is part of an automated job, to ensure all the processes spun will be terminated.
A sample line from the command line, when ps aux | grep com.scheduler.app.workermain is executed is:
jenkins 12373 1.1 4.2 2905440 173628 ? Sl 19:28 0:05 java -Xmx600m -Dlog4j.configurationFile=log4j2-trace.xml -Dpid=foobar -Dipaddr=127.0.0.1 -cp build/classes:build/dependency/* com.scheduler.app.workermain testing.properties
pkill is used for exactly this purpose. How about:
pkill -15 -f com.scheduler.app.workermain
Also if you just want to grep for a PID you can use pgrep:
pgrep -f com.scheduler.app.workermain
pkill man page
kill -15 $(ps aux | grep -i com.scheduler.app.workermain | awk -F' ' '{ print $2 }')
One of possible solutions is to use the pidof command:
kill $( pidof com.scheduler.app.workermain )
PS. You don't need to pass -15 (or -TERM) to the kill command, as SIGTERM is the default signal sent.

linux script to kill java process

I want linux script to kill java program running on console.
Following is the process running as jar.
[rapp#s1-dlap0 ~]$ ps -ef |grep java
rapp 9473 1 0 15:03 pts/1 00:00:15 java -jar wskInterface-0.0.1-SNAPSHOT-jar-with-dependencies.jar
rapp 10177 8995 0 16:00 pts/1 00:00:00 grep java
[rapp#s1-dlap0 ~]$
You can simply use pkill -f like this:
pkill -f 'java -jar'
EDIT: To kill a particular java process running your specific jar use this regex based pkill command:
pkill -f 'java.*lnwskInterface'
If you just want to kill any/all java processes, then all you need is;
killall java
If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;
PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID
Should do it, there is probably an easier way though...
if there are multiple java processes and you wish to kill them with one command
try the below command
kill -9 $(ps -ef | pgrep -f "java")
replace "java" with any process string identifier , to kill anything else.
pkill -f for whatever reason does not work for me. Whatever that does, it seems very finicky about actually grepping through what ps aux shows me clearly is there.
After an afternoon of swearing I went for putting the following in my start script:
(ps aux | grep -v -e 'grep ' | grep MainApp | tr -s " " | cut -d " " -f 2 | xargs kill -9 ) || true
Use jps to list running java processes. The command returns the process id along with the main class. You can use kill command to kill the process with the returned id or use following one liner script.
kill $(jps | grep <MainClass> | awk '{print $1}')
MainClass is a class in your running java program which contains the main method.

How can I kill a process by name instead of PID, on Linux? [duplicate]

This question already has answers here:
Find and kill a process in one line using bash and regex
(30 answers)
Closed 1 year ago.
Sometimes when I try to start Firefox it says "a Firefox process is already running". So I have to do this:
jeremy#jeremy-desktop:~$ ps aux | grep firefox
jeremy 7451 25.0 27.4 170536 65680 ? Sl 22:39 1:18 /usr/lib/firefox-3.0.1/firefox
jeremy 7578 0.0 0.3 3004 768 pts/0 S+ 22:44 0:00 grep firefox
jeremy#jeremy-desktop:~$ kill 7451
What I'd like is a command that would do all that for me. It would take an input string and grep for it (or whatever) in the list of processes, and would kill all the processes in the output:
jeremy#jeremy-desktop:~$ killbyname firefox
I tried doing it in PHP but exec('ps aux') seems to only show processes that have been executed with exec() in the PHP script itself (so the only process it shows is itself.)
pkill firefox
More information: http://linux.about.com/library/cmd/blcmdl1_pkill.htm
Also possible to use:
pkill -f "Process name"
For me, it worked up perfectly. It was what I have been looking for.
pkill doesn't work with name without the flag.
When -f is set, the full command line is used for pattern matching.
You can kill processes by name with killall <name>
killall sends a signal to all
processes running any of the specified
commands. If no signal name is
specified, SIGTERM is sent.
Signals can be specified either by
name (e.g. -HUP or -SIGHUP ) or by number (e.g.
-1) or by option -s.
If the command name is not regular
expression (option -r) and contains a
slash (/), processes executing that
particular file will be selected for
killing, independent of their name.
But if you don't see the process with ps aux, you probably won't have the right to kill it ...
A bit longer alternative:
kill `pidof firefox`
The easiest way to do is first check you are getting right process IDs with:
pgrep -f [part_of_a_command]
If the result is as expected. Go with:
pkill -f [part_of_a_command]
If processes get stuck and are unable to accomplish the request you can use kill.
kill -9 $(pgrep -f [part_of_a_command])
If you want to be on the safe side and only terminate processes that you initially started add -u along with your username
pkill -f [part_of_a_command] -u [username]
Kill all processes having snippet in startup path. You can kill all apps started from some directory by for putting /directory/ as a snippet. This is quite usefull when you start several components for the same application from the same app directory.
ps ax | grep <snippet> | grep -v grep | awk '{print $1}' | xargs kill
* I would prefer pgrep if available
Strange, but I haven't seen the solution like this:
kill -9 `pidof firefox`
it can also kill multiple processes (multiple pids) like:
kill -9 `pgrep firefox`
I prefer pidof since it has single line output:
> pgrep firefox
6316
6565
> pidof firefox
6565 6316
Using killall command:
killall processname
Use -9 or -KILL to forcefully kill the program (the options are similar to the kill command).
On Mac I could not find the pgrep and pkill neither was killall working so wrote a simple one liner script:-
export pid=`ps | grep process_name | awk 'NR==1{print $1}' | cut -d' ' -f1`;kill $pid
If there's an easier way of doing this then please share.
To kill with grep:
kill -9 `pgrep myprocess`
more correct would be:
export pid=`ps aux | grep process_name | awk 'NR==1{print $2}' | cut -d' ' -f1`;kill -9 $pid
I normally use the killall command.
Check this link for details of this command.
I was asking myself the same question but the problem with the current answers is that they don't safe check the processes to be killed so... it could lead to terrible mistakes :)... especially if several processes matches the pattern.
As a disclaimer, I'm not a sh pro and there is certainly room for improvement.
So I wrote a little sh script :
#!/bin/sh
killables=$(ps aux | grep $1 | grep -v mykill | grep -v grep)
if [ ! "${killables}" = "" ]
then
echo "You are going to kill some process:"
echo "${killables}"
else
echo "No process with the pattern $1 found."
return
fi
echo -n "Is it ok?(Y/N)"
read input
if [ "$input" = "Y" ]
then
for pid in $(echo "${killables}" | awk '{print $2}')
do
echo killing $pid "..."
kill $pid
echo $pid killed
done
fi
kill -9 $(ps aux | grep -e myprocessname| awk '{ print $2 }')
If you run GNOME, you can use the system monitor (System->Administration->System Monitor) to kill processes as you would under Windows. KDE will have something similar.
The default kill command accepts command names as an alternative to PID. See kill (1). An often occurring trouble is that bash provides its own kill which accepts job numbers, like kill %1, but not command names. This hinders the default command. If the former functionality is more useful to you than the latter, you can disable the bash version by calling
enable -n kill
For more info see kill and enable entries in bash (1).
ps aux | grep processname | cut -d' ' -f7 | xargs kill -9 $
awk oneliner, which parses the header of ps output, so you don't need to care about column numbers (but column names). Support regex. For example, to kill all processes, which executable name (without path) contains word "firefox" try
ps -fe | awk 'NR==1{for (i=1; i<=NF; i++) {if ($i=="COMMAND") Ncmd=i; else if ($i=="PID") Npid=i} if (!Ncmd || !Npid) {print "wrong or no header" > "/dev/stderr"; exit} }$Ncmd~"/"name"$"{print "killing "$Ncmd" with PID " $Npid; system("kill "$Npid)}' name=.*firefox.*

Resources