Monitor Linux Processes with a Simple Shell Script
This guide shows how to create a reusable shell function that retrieves a process ID for a given user and program, demonstrates its usage, and explains each command involved so you can reliably detect when a service stops running.
In daily operations, ensuring that critical services stay alive is essential; when a process exits, it often signals a problem that must be addressed immediately. This article provides a practical shell script to continuously check whether a specific process is running.
The core function GetPID accepts two arguments—the username and the process name—and returns the PID of the matching process. It uses ps -u $PsUser to list processes for the user, pipes the output through several grep filters to exclude irrelevant entries (such as the grep command itself, editors, or auxiliary scripts), then extracts the first PID with sed -n 1p and awk '{print $1}'.
function GetPID #User #Name {
PsUser=$1
PsName=$2
pid=`ps -u $PsUser | grep $PsName | grep -v grep | grep -v vi | grep -v dbx \
| grep -v tail | grep -v start | grep -v stop | sed -n 1p | awk '{print $1}'`
echo $pid
}Example usage:
PID=`GetPID root TestApp`
echo $PIDThe command prints the PID (e.g., 11426) of the TestApp process running under the root user. If the process is not found, the function returns an empty string, which can be checked as follows:
if [ "-$PID" == "-" ]; then
echo "The process does not exist."
fiCommand breakdown:
ps : displays a snapshot of current processes. Option -u limits output to a specific user.
grep : filters lines containing the target process name; -v inverts the match to exclude unwanted lines.
sed : a stream editor; -n 1p prints only the first matching line.
awk : processes text columns; {print $1} extracts the first field, which is the PID.
By integrating this function into monitoring scripts or cron jobs, administrators can automatically detect when a service stops and trigger alerts or restart procedures.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
