Bash Script to Check if Service is Running
systemctl is-active --quiet service_name in a Bash script and check the exit status to see if the service is running; if the exit status is 0, the service is running.Examples
How to Think About It
systemctl is-active. Then, it should look at the command's exit code: if it is zero, the service is running; otherwise, it is not. This simple check avoids parsing output text and is reliable.Algorithm
Code
#!/bin/bash service_name="$1" if systemctl is-active --quiet "$service_name"; then echo "Service $service_name is running" else echo "Service $service_name is not running" fi
Dry Run
Let's trace checking the service 'ssh' through the code
Get service name
service_name="ssh"
Run systemctl check
systemctl is-active --quiet ssh (exit status 0 if running)
Check exit status
Exit status is 0, so service is running
Print result
Output: Service ssh is running
| Step | Command | Exit Status | Output |
|---|---|---|---|
| 2 | systemctl is-active --quiet ssh | 0 | |
| 4 | echo message | Service ssh is running |
Why This Works
Step 1: Use systemctl is-active
The command systemctl is-active --quiet service_name checks if the service is running without printing output.
Step 2: Check exit status
If the exit status is 0, it means the service is active; any other status means it is not.
Step 3: Print user-friendly message
Based on the exit status, the script prints a clear message about the service status.
Alternative Approaches
#!/bin/bash service_name="$1" if service "$service_name" status > /dev/null 2>&1; then echo "Service $service_name is running" else echo "Service $service_name is not running" fi
#!/bin/bash service_name="$1" if pidof "$service_name" > /dev/null; then echo "Service $service_name is running" else echo "Service $service_name is not running" fi
Complexity: O(1) time, O(1) space
Time Complexity
The check runs a single system command which completes in constant time regardless of service state.
Space Complexity
The script uses a fixed amount of memory for variables and command execution, so space is constant.
Which Approach is Fastest?
Using systemctl is-active --quiet is fastest and most reliable on modern systems; alternatives may be slower or less accurate.
| Approach | Time | Space | Best For |
|---|---|---|---|
| systemctl is-active | O(1) | O(1) | Modern Linux systems with systemd |
| service status | O(1) | O(1) | Older Linux systems without systemd |
| pidof | O(1) | O(1) | Quick process name check, less reliable |
systemctl is-active --quiet and check the exit code for a clean service status check.