If you're looking for a regex expression which can validate the format of a CRON time expression (for most versions of CRON) you've probably had a look at StackOverflow and had to trapse through a bunch of possible expressions which may not quite work.
Credit to Juarez and Slava who collectively derived the expression below here: https://stackoverflow.com/questions/14203122/create-a-regular-expression-for-cron-statement/63729682#63729682
^((((\d+,)+\d+|(\d+(\/|-|#)\d+)|\d+L?|\*(\/\d+)?|L(-\d+)?|\?|[A-Z]{3}(-[A-Z]{3})?) ?){5,7})|(@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|µs|ms|s|m|h))+)$
Warning
This is intended to validate ONLY the time expression, not a line from a CRON file.
If you're interested in what this looks like in use, have a look at: https://regex101.com/r/RtLgqG/
If you use this, take care to check which version of CRON expressions are supported and amend this regex as needed, i.e. removing specific parts between the OR "|" pipe symbols.
e.g. if your version of CRON does not support the @TIME expressions:
^((((\d+,)+\d+|(\d+(\/|-|#)\d+)|\d+L?|\*(\/\d+)?|L(-\d+)?|\?|[A-Z]{3}(-[A-Z]{3})?) ?){5,7})$
These examples use the full expression.
#!/bin/bash
validate_cron_expression() {
local cron_expression="$1"
local regex='^((((\d+,)+\d+|(\d+(\/|-|#)\d+)|\d+L?|\*(\/\d+)?|L(-\d+)?|\?|[A-Z]{3}(-[A-Z]{3})?) ?){5,7})|(@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|µs|ms|s|m|h))+)$'
if echo "$cron_expression" | grep -Pq "$regex"; then
return 0 # Valid cron expression
else
return 1 # Invalid cron expression
fi
}
# Example usage:
cron_expression="* * * * *"
if validate_cron_expression "$cron_expression"; then
echo "Valid cron expression: $cron_expression"
else
echo "Invalid cron expression: $cron_expression"
fi
Note
In the context of bash scripting:
- If a command or function completes successfully without any errors, it typically returns an exit status of 0.
- If there is an error or the command/function encounters an issue, it returns a non-zero exit status to indicate failure.
When we check the return value of the validate_cron_expression function using the if statement, we're checking if the function returned true (0) or false (non-zero).
#!/usr/bin/env python3
import re
def validate_cron_expression(cron_expression):
regex = '^((((\d+,)+\d+|(\d+(\/|-|#)\d+)|\d+L?|\*(\/\d+)?|L(-\d+)?|\?|[A-Z]{3}(-[A-Z]{3})?) ?){5,7})|(@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|µs|ms|s|m|h))+)$'
if re.match(regex, cron_expression):
return True # Valid cron expression
else:
return False # Invalid cron expression
# Example usage:
cron_expression = "* * * * *"
if validate_cron_expression(cron_expression):
print(f"Valid cron expression: {cron_expression}")
else:
print(f"Invalid cron expression: {cron_expression}")