I need to get a PID of a process by name in bash script. I cannot use pidof
as it is not available on my Linux distribution and I cannot install that.
$ ps aux | grep name_of_process
user 1111 0.0 03:20 0:00 grep name_of_process
user2 2222 2.4 03:11 0:13 -Dappsrv.root=/dir1/dir2/dir2/tomcat/name_of_process
I tried the following solution but it gives my two pids each time and in random order thus it is no use:
OUTPUT=$( pgrep -f name_of_process )
VARS=( $OUTPUT )
echo $VARS #1111 2222
I also tried:
ps -ef | awk '$8=="name_of_process" {print $2}'
But that does not return anything
I need to kill that process but each time from command
sudo -u root kill -9 `ps -ef | grep '[n]ame_of_process' | awk '{print $2}'`
170497
181212
kill 170497: Operation not permitted
kill 181216: No such process
CodePudding user response:
Your pgrep approach looks basically reasonable for me, but why are you using -f
?
VARS=( $(pgrep name_of_process) )
should be sufficient. But be careful with the process name: pgrep
interprets the argument as extended regular expression, and when your process name contains i.e. .
or
or other regex characters, the outcome is not necessarily what you expect.
CodePudding user response:
If anyone will encounter the same problem: My script name contained name of the process therefore when I was trying to get the PID of the process by it's name it found two process: one for the actual process and second for my script name.
CodePudding user response:
It's simple:
- Type
ps aux
- this command get you all process - Filter process by name with
| grep PROCESS_NAME
- Now from the output get the
PID
of the process from second column with|awk '{print $2}'
Like this:
ps aux| grep PROCESS_NAME|awk '{print $2}'