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
- How would you write a health-check script that polls a URL until it returns 200? [Advanced]
- What is the difference between a cron job and a systemd timer? [Advanced]
- What is the difference between sed -i and sed without -i? [Advanced]
- What is idempotency, and how do you make a script safe to run repeatedly? [Advanced]
- How do you use awk to sum or average a column? [Advanced]
- How do you securely handle secrets in a shell script (avoid hardcoding, use env or a vault)? [Advanced]
- What is the difference between NR and NF in awk? [Advanced]
- How do you split a string on a delimiter in Bash? [Intermediate]