Checking and Starting cron from a Script (2 Approaches)

Roy HaydenRoy Hayden
2 min read

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 using service 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 interface

  • Won’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 starts cron

Key Differences

FeatureScript 1Script 2
MethodChecks exit statusParses command output
SecurityUses interactive sudoPipes hardcoded password to sudo
RobustnessSafer, doesn’t rely on exact textFragile (breaks if output changes)
User feedbackVerbose messages with ✓/✗Silent unless added manually
Recommended?YesNo (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 using sudo.

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.

0
Subscribe to my newsletter

Read articles from Roy Hayden directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Roy Hayden
Roy Hayden