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.
The answer above was mostly correct, just needed some tweaking for the different parameters in Mac OSX.
ps -A | grep -m1 firefox | awk '{print $1}'
You can install pidof
with Homebrew:
brew install pidof
pidof <process_name>
You can use the pgrep command like in the following example
$ pgrep Keychain\ Access
44186
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.
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.
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
You can try this
pid=$(ps -o pid=,comm= | grep -m1 $procname | cut -d' ' -f1)
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