Getting PID by Name on FreeBSD
Filed under: freebsd
This post covers getting the PID of a process by name with and without the sysutils/psmisc port.
Software Versions
$ date
February 19, 2016 at 07:57:31 PM JST
$ uname -vm
FreeBSD 11.0-CURRENT #0 r287598: Thu Sep 10 14:45:48 JST 2015 root@:/usr/obj/usr/src/sys/MIRAGE_KERNEL amd64Instructions
EDIT:
Just use pgrep. The following example uses pgrep in a script.
is_running.sh
#!/bin/sh
PROCESS_NAME=$1
USER=$(whoami)
if pgrep -q -U "${USER}" -x "${PROCESS_NAME}"
then
echo "${PROCESS_NAME} is running as user '${USER}'."
else
echo "${PROCESS_NAME} is not running as user '${USER}'."
fi/EDIT
The easy way is to install the sysutils/psmisc port and use the pidof command.
portmaster sysutils/psmisc
PROCESS_NAME="sshd"
pidof "${PROCESS_NAME}"The following can be used to get the information on all of the processes matching a name.
PROCESS_NAME="sshd" ; ps -aux | grep "${PROCESS_NAME}" | grep -v "grep"The following can be used to get the PIDs of all processes matching a name.
PROCESS_NAME="sshd" ; ps -ax | grep "${PROCESS_NAME}" | grep -v "grep" | awk '{ print $1 }'Something like the following can be used for control flow in a shell script. The -qs flags suppress grep output.
#!/bin/sh
PROCESS_NAME="sshd"
if ps -ax | grep "${PROCESS_NAME}" | grep -qsv "grep"
then
echo "${PROCESS_NAME} is running."
else
echo "${PROCESS_NAME} is not running."
fiReferences
Primary Sources, Non-Peer-Reviewed
- “FreeBSD, man pgrep.” n.d. www.freebsd.org. Accessed October 25, 2026. https://www.freebsd.org/cgi/man.cgi?query=pgrep&sektion=1
- “FreeBSD, man pidof.” n.d. www.freebsd.org. Accessed October 25, 2026. https://www.freebsd.org/cgi/man.cgi?query=pidof&manpath=SuSE+Linux/i386+11.3
- “sgeos.github.io Post History.” n.d. github.com. Accessed October 25, 2026. https://github.com/sgeos/sgeos.github.io/commit/5c4dcf97faced6fefe5e29e4a8c95ed94ce599ef
General Sources
- “FreeBSD, Fresh Ports sysutils/psmisc.” n.d. Accessed October 25, 2026. https://www.freshports.org/sysutils/psmisc
- “Note to Self: How to Terminate Process by Name in UNIX.” n.d. Accessed October 25, 2026. http://notetodogself.blogspot.com/2006/07/how-to-terminate-process-by-name-in.html