Interview Scripting (Bash, Groovy)

How would you write a script to check if a process is running and restart it? [Advanced]

Answer

I would check process state using systemd when available, because it is the service manager and can restart reliably. If systemd is not available, use pgrep with an exact pattern and then start the process with a controlled command.

Technical explanation

Prefer systemctl is-active and systemctl restart for managed services instead of grepping ps output.

If using pgrep, use -f carefully and avoid matching the grep command or unrelated processes.

Log restart attempts and add rate limiting to avoid restart loops.

Hands-on example

#!/usr/bin/env bash

set -euo pipefail

service="nginx"

if ! systemctl is-active --quiet "$service"; then

echo "$service is down; restarting" >&2

systemctl restart "$service"

fi

systemctl is-active --quiet "$service

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Scripting (Bash, Groovy) interview questions

← All Scripting (Bash, Groovy) questions