Checking and Starting cron from a Script (2 Approaches)

Sometimes I want to make sure my cron
daemon is running, especially after a reboot or on a system where it might silently stop. Here's how I scripted that check, with two different approaches.
Script 1: Check and Start cron
(Clean and Verbose)
#!/bin/bash
# Check the status of cron using 'service'
if service cron status >/dev/null 2>&1; then
echo "Cron is detected to be running ✓ "
else
echo "Cron not running, starting..."
if sudo service cron start >/dev/null 2>&1; then
echo "Cron has been started ✓"
else
echo "Failed to start Cron"
exit 1
fi
fi
echo
What it does:
Silently checks if
cron
is running usingservice cron status
If running, it prints a confirmation
If not, it attempts to start the service via
sudo
Includes fallback error handling and success/failure output
Why it's reliable:
Clear structure
Doesn't rely on parsing output strings
Safer and more portable across distros using the classic
service
interfaceWon’t break if the exact wording of
cron status
changes
Script 2: Check cron
Using Output Parsing (Quicker but Fragile)
#!/bin/bash
cronstatus=$(service cron status | cut -c 4-)
if [ "$cronstatus" == "cron is not running" ]; then
echo password123 | sudo -S service cron start
fi
What it does:
Captures the output of
service cron status
Trims the first 3 characters using
cut -c 4-
Compares the string to
cron is not running
If it matches, pipes a hardcoded password to
sudo
and startscron
Key Differences
Feature | Script 1 | Script 2 |
Method | Checks exit status | Parses command output |
Security | Uses interactive sudo | Pipes hardcoded password to sudo |
Robustness | Safer, doesn’t rely on exact text | Fragile (breaks if output changes) |
User feedback | Verbose messages with ✓/✗ | Silent unless added manually |
Recommended? | Yes | No (see below) |
My Thoughts
While Script 2 might feel quicker to write, it's brittle and not secure:
Parsing the exact output of
service
is risky. Messages can vary between distros or updates.Hardcoding your
sudo
password is dangerous and defeats the point of usingsudo
.
Stick with Script 1. It’s safer, clearer, and easier to maintain.
Bonus: Cron Check on Startup
If you want to make sure cron
is running every time your system boots, you could run Script 1 from a @reboot
crontab entry or a systemd service.
But for WSL on a home workstation, the above is sufficient.
Subscribe to my newsletter
Read articles from Roy Hayden directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
