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
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
- What is the purpose of the shebang line, and what does #!/bin/bash do? [Basic]
- What is the difference between sh and bash? [Basic]
- How do you make a script executable and run it? [Basic]
- What is the difference between running a script with ./script.sh, bash script.sh, and source script.sh? [Basic]
- What does sourcing a script do differently from executing it? [Basic]
- How do you declare a variable in Bash, and why are spaces around = not allowed? [Basic]
- What is the difference between $var and ${var}? [Basic]
- What is the difference between single quotes and double quotes in Bash? [Basic]