Linux/Bash, Using Ps -O to Get Process by Specific Name

Linux / Bash, using ps -o to get process by specific name?

This will get you the PID of a process by name:

pidof name

Which you can then plug back in to ps for more detail:

ps -p $(pidof name)

Bash generic ps aux process by strict name

OK I guess I found it, really easy and straightforward:

ps -e -o pid,comm | grep ssh-agent

Works just fine.

Answer found here: https://unix.stackexchange.com/questions/22892/how-do-use-awk-along-with-a-command-to-show-the-process-id-with-the-ps-command/22895#22895

And adapted with a | grep ssh-agent

Also suggested by Martin. Thank you all for sharing your experience!

How to get only process ID in specify process name in Linux?

You can use:

ps -ef | grep '[j]ava'

Or if pgrep is available then better to use:

pgrep -f java

bash ps print info about process with name

You can always use the two-stage approach.

1.) find the wanted PIDs. For this use the simplest possible ps

ps -o pid,comm | grep "$2" | cut -f1 -d' '

the ps -o pid,comm prints only two columns, like:

67676 -bash
71548 -bash
71995 -bash
72219 man
72220 sh
72221 sh
72225 sh
72227 /usr/bin/less
74364 -bash

so grepping it is easy (and noise-less, without false triggers). The cut just extracts the PIDs. E.g. the

ps -o pid,comm | grep bash | cut -f1 -d' '

prints

67676
71548
71995
74364

2.) and now you can feed the found PIDs to the another ps using the -p flag, so the full command is:

ps -o uid,pid,ppid,ni,vsz,rss,stat,tty,time,command -p $(ps -o pid,comm | grep bash | cut -f1 -d' ')

output

  UID   PID  PPID NI      VSZ    RSS STAT TTY           TIME COMMAND
501 67676 67675 0 2499876 7212 S+ ttys000 0:00.04 -bash
501 71548 71547 0 2500900 8080 S ttys001 0:01.81 -bash
501 71995 71994 0 2457892 3616 S ttys002 0:00.04 -bash
501 74364 74363 0 2466084 7176 S+ ttys003 0:00.06 -bash

e.g. the solution using the $2 is

ps -o uid,pid,ppid,ni,vsz,rss,stat,tty,time,command -p $(ps -o pid,comm | grep "$2" | cut -f1 -d' ')

How to get PID of process by specifying process name and store it in a variable to use further?

If you want to kill -9 based on a string (you might want to try kill first) you can do something like this:

ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}'

This will show you what you're about to kill (very, very important) and just pipe it to sh when the time comes to execute:

ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}' | sh


Related Topics



Leave a reply



Submit