Getting pids from ps -ef |grep keyword - linux

I want to use ps -ef | grep "keyword" to determine the pid of a daemon process (there is a unique string in output of ps -ef in it).
I can kill the process with pkill keyword is there any command that returns the pid instead of killing it? (pidof or pgrep doesnt work)

You can use pgrep as long as you include the -f options. That makes pgrep match keywords in the whole command (including arguments) instead of just the process name.
pgrep -f keyword
From the man page:
-f The pattern is normally only matched against the process name. When -f is set, the full command line is used.
If you really want to avoid pgrep, try:
ps -ef | awk '/[k]eyword/{print $2}'
Note the [] around the first letter of the keyword. That's a useful trick to avoid matching the awk command itself.

Try
ps -ef | grep "KEYWORD" | awk '{print $2}'
That command should give you the PID of the processes with KEYWORD in them. In this instance, awk is returning what is in the 2nd column from the output.

ps -ef | grep KEYWORD | grep -v grep | awk '{print $2}'

This is available on linux: pidof keyword

I use
ps -C "keyword" -o pid=
This command should give you a PID number.

To kill a process by a specific keyword you could create an alias in ~/.bashrc (linux) or ~/.bash_profile (mac).
alias killps="kill -9 `ps -ef | grep '[k]eyword' | awk '{print $2}'`"

Related

.bashrc saves previous process id and does not update in alias commands

I have made an alias in .bashrc to kill my python service.py & process
alias servicestop="kill $(ps -ef | grep -w service.py | grep -v grep | awk '{print $2}')"
Whenever I run first time servicestop command it will kill the process.
but again whenever I start process python service.py &, and execute command servicestop it gives an error.
After research, I found following things.
when I run first time python service.py & process. its process id was 512.
and, command servicestop kill that process(512).
Now when I run Second time process python service.py &. its process id was 546.(definitely it will be different).
When I run command servicestop. it will give following error:
-bash: kill: (512) - No such process
That means $(ps -ef | grep -w service.py | grep -v grep | awk '{print $2}') will return the previous pid, which is already killed.
Now please suggest the solution if any possible.
so whenever I want to run servicestop command, I have to run source .bashrc command first, then run servicestop command to make it work.
Please remove the servicestop alias from your .bashrc and add :
servicestop(){
kill $(ps -ef | grep -w service.py | grep -v grep | awk '{print $2}');
}
In a way, functions in .bashrc are "aliases 2.0" : simply better
Better : same function; but with the name of script to kill as parameter :
servicestop(){
kill $(ps -ef | grep -w $1 | grep -v servicestop | awk '{print $2}');
}
Use it like that :
servicestop service.py
servicestop otherSuperService.py

how can I kill a process in a shell script

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.

Linux Script to selectively kill processes

I'm looking at a way to automate the following:
Run ps -ef to list all processes.
Filter out those rows containing java in the CMD column.
Filter out those rows containing root in the UID column.
For each of the filtered rows, get the PID column and run pargs <PID>.
If the output of pargs <PID> contains a particular string XYZ, the issue a kill -9 <PID> command.
To filter out rows based on specific column values, is there a better way than grep? I can use
ps -ef | awk '{print $1}' | grep <UID>
but then I lose info from all other columns. The closest thing I have right now is:
ps -ef | grep java | grep root | grep -v grep | xargs pargs | ?????
EDIT
I was able to solve the problem by using a using the following script:
ps -ef | awk '/[j]ava/ && /root/ {print $2}' | while read PID; do
pargs "$PID" | grep "Args" > /dev/null && kill -9 $PID && echo "$PID : Java process killed!"
done
both anubhava's and kojiro's answers helped me reach there. But since I can only accept one answer, I tagged kojiro's answer as the correct one since it helped me a bit more.
Consider pgrep:
pgrep -U 0 java | while read pid; do
pargs "$pid" | grep -qF XYZ && kill "$pid"
done
pgrep and pkill are available on many Linux systems and as part of the "proctools" packages for *BSDs and OS X.
You can reduce all grep by using awk:
ps -ef | awk '/[j]ava/ && /root/ {print $1}' | xargs pargs
Searching for pattern /[j]ava/ will skip this awk process from output of ps.
You can also use pkill if it is available on your system.

Getting PID of process in Shell Script

I am writing one shell script and I want to get PID of one process with name as "ABCD". What i did was :
process_id=`/bin/ps -fu $USER|grep "ABCD"|awk '{print $2}'`
This gets PID of two processes i.e. of process ABCD and the GREP command itself what if I don't want to get PID of GREP executed and I want PID only of ABCD process?
Please suggest.
Just grep away grep itself!
process_id=`/bin/ps -fu $USER| grep "ABCD" | grep -v "grep" | awk '{print $2}'`
Have you tried to use pidof ABCD ?
It's very straight forward. ABCD should be replaced by your process name.
#!/bin/bash
processId=$(ps -ef | grep 'ABCD' | grep -v 'grep' | awk '{ printf $2 }')
echo $processId
Sometimes you need to replace ABCD by software name. Example - if you run a java program like java -jar TestJar.jar & then you need to replace ABCD by TestJar.jar.
ps has an option for that:
process_id=`/bin/ps -C ABCD -o pid=`
You can also do away with grep and use only awk.
Use awk's expression matching to match the process name but not itself.
/bin/ps -fu $USER | awk '/ABCD/ && !/awk/ {print $2}'
You can use this command to grep the pid of a particular process & echo $b to print pid of any running process:
b=`ps -ef | grep [A]BCD | awk '{ printf $2 }'`
echo $b
ps | pgrep ABCD
You can try the above command to return the process id of the ABCD process.
I found a better way to do this.
top -n 1 | grep "##" | grep -Eo '^[^ ]+'

Kill random process with name

I want a way to kill a random process with a name (eg a random perl process).
What would be the best way of doing this?
I was thinkign of using something like this:
ps aux | grep PROCESS-NAME
to a file, then find a random line number, get the second column (process ID?) and kill that.
For my use it doesn't actually need to be a random one, as long as it kills one of the processes. Making it random just makes it better.
look at the -r option of the killall command!
Bash one-liner :-p
kill `ps auxww | grep zsh | awk '{print $2}' | while read line; do echo "$RANDOM $line"; done | sort | cut -d ' ' -f 2 | head -n 1`
There's also the 'pidof' command, which can be used to kill with:
kill `pidof processname`
To get just one process when there are multiple with the same name, use -s for "single shot".
It sounded like you were already on the right track.
you can use the following perl script, save it as randomline.pl, which will return a random line from whats piped into it
#!/usr/bin/perl
srand (time ^ $$ ^ unpack "%L*", `ps axww | gzip`);
while (<>) { push(#_,$_); } print #_[rand()*#_];
then run the following command to send the kill command
kill `ps aux | grep PROCESS-NAME | perl randomline.pl | awk '{print $2}'`
You might also want to add in some checking, perhaps with an inverted grep for root to make sure you don't try to kill root level processes that match your process name.
just kill and awk.
kill $(ps -eo cmd,pid|awk '/zsh/&&!/awk/{pid[$NF]}END{for(i in pid){print i;exit}}')
the for loop in the END block will give you you a random pid to kill
with recent bash shell
#!/bin/bash
declare -a pid
pid=( $(pidof myprocess) )
length=${#pid}
rnumber=$((RANDOM%length+1))
rand=$((rnumber-1))
kill ${pid[$rand]}
How about using pgrep and pkill. They allow lot of options to select the processes.
kill process with name "my_proc_name" :
kill -9 `ps xf | grep my_proc_name | grep -v grep | cut -d " " -f 1`
Maybe off topic, but I use this on Cygwin. Inspired by
Lev Victorovich Priyma’s answer
ps -W | awk '/calc.exe/,NF=1' | xargs kill -f
or
ps -W | awk '$0~z,NF=1' z=calc.exe | xargs kill -f

Resources