Getting the PID of a process by name with and without the sysutils/psmisc port.

Instructions:

The fallow example uses pgrep in a bash script file:

#!/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

The easy way is to install sysutils/psmisc port and use the pidof command:

portmaster sysutils/psmisc
PROCESS_NAME="sshd"
pidof "${PROCESS_NAME}"

Fallowing command can by used to get information to all of the processes matching a name:

PROCESS_NAME="sshd" ; ps -aux | grep "${PROCESS_NAME}" | grep -v "grep"

Fallowing command 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 }'

Below script can be used to controll flow in a shell script. The -qs flags supress 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."
fi

Reference:

  1. FreeBSD, man pgrep
  2. How to terminate process by name in UNIX

My site is free of ads and trackers. Was this post helpful to you? Why not BuyMeACoffee