Process Management and AutomationLesson 5.4
How to monitor and manage Bash script processes
ps and pgrep, kill and pkill, pidfile pattern, wait with timeout, process substitution, /proc filesystem, lsof for open files, monitoring script health with while loop
Finding and Managing Processes
Scripts that run as daemons or long-running tasks need a way to track and manage themselves.
# PID file pattern โ track your script's process
PIDFILE="/var/run/myscript.pid"
# On start: write PID
echo $$ > "$PIDFILE"
trap "rm -f $PIDFILE" EXIT
# Check if another instance is running
if [[ -f "$PIDFILE" ]]; then
old_pid=$(cat "$PIDFILE")
if kill -0 "$old_pid" 2>/dev/null; then
echo "Script already running (PID $old_pid)" >&2
exit 1
fi
rm -f "$PIDFILE" # stale PID file
fiFinding Processes
# pgrep/pkill are cleaner than ps | grep
pgrep -f "myapp.sh" # PIDs of matching processes
pkill -TERM -f "myapp.sh" # send SIGTERM
# Check if a process is alive
if kill -0 "$pid" 2>/dev/null; then
echo "Process $pid is running"
fiWait with Timeout
wait_for_process() {
local pid=$1 timeout=$2 elapsed=0
while kill -0 "$pid" 2>/dev/null; do
if (( elapsed >= timeout )); then
echo "Timeout waiting for PID $pid" >&2
return 1
fi
sleep 1
(( elapsed++ ))
done
}kill -0 PID doesn't send a signal โ it just checks if the process exists. Exit code 0 = running, non-zero = not found.
