How to get the PID of a process by giving the process name in Mac OS X ?
MacosBashShellProcessPidMacos Problem Overview
I am writing a script to monitor the CPU and MEM of any given process. For that i need to send in the name of the process to be monitored as a commandline argument. For example.
./monitorscript <pname>
I need to get the pid of the process in the script so that i can use a ps -p <pid>
inside.
How do i get the pid of a process given its process name?
I understand that there might be multiple processes in the same name. I just want to get the first process out of that list.
Macos Solutions
Solution 1 - Macos
The answer above was mostly correct, just needed some tweaking for the different parameters in Mac OSX.
ps -A | grep [f]irefox | awk '{print $1}'
Solution 2 - Macos
You can use the pgrep command like in the following example
$ pgrep Keychain\ Access
44186
Solution 3 - Macos
You can install pidof
with Homebrew:
brew install pidof
pidof <process_name>
Solution 4 - Macos
This solution matches the process name more strictly:
ps -Ac -o pid,comm | awk '/^ *[0-9]+ Dropbox$/ {print $1}'
This solution has the following advantages:
- it ignores command line arguments like
tail -f ~/Dropbox
- it ignores processes inside a directory like
~/Dropbox/foo.sh
- it ignores processes with names like
~/DropboxUID.sh
Solution 5 - Macos
This is the shortest command I could find that does the job:
ps -ax | awk '/[t]he_app_name/{print $1}'
Putting brackets around the first letter stops awk from finding the awk process itself.
Solution 6 - Macos
Try this one:
echo "$(ps -ceo pid=,comm= | awk '/firefox/ { print $1; exit }')"
The ps
command produces output like this, with the PID in the first column and the executable name (only) in the second column:
bookworm% ps -ceo pid=,comm=
1 launchd
10 kextd
11 UserEventAgent
12 mDNSResponder
13 opendirectoryd
14 notifyd
15 configd
...which awk
processes, printing the first column (pid) and exiting after the first match.
Solution 7 - Macos
You can try this
pid=$(ps -o pid=,comm= | grep -m1 $procname | cut -d' ' -f1)
Solution 8 - Macos
ps -o ppid=$(ps -ax | grep nameOfProcess | awk '{print $1}')
Prints out the changing process pid and then the parent PID. You can then kill the parent, or you can use that parentPID in the following command to get the name of the parent process:
ps -p parentPID -o comm=
For me the parent was 'login' :\
Solution 9 - Macos
Why don't you run TOP and use the options to sort by other metrics, other than PID? Like, highest used PID from the CPU/MEM?
top -o cpu <---sorts all processes by CPU Usage