Read more

How to show an ordered crontab

Arne Hartherz
March 14, 2017Software engineer at makandra GmbH

Crontabs are often unordered, especially when generated for an application where you usually group tasks by their domain/scope.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

An example crontab might look like this:

# Begin Whenever generated tasks for: project100
MAILTO="log@example.com"
MAILFROM="cron@example.com"

# When server is booting up, ensure Sidekiq is running
@reboot start_sidekiq

23 8 * * * baz
30 * * * * plop
5 8 * * * bar
1 0 * * * foo
# End Whenever generated tasks for: project100

While you can human-parse this one easily, crontabs with several lines are hard to read.

The following command will ignore any comments or environment variables, and order rows by their hour (k2) and minute (k1). Note how numbers are ordered naturally (5 before 23).

crontab -l | grep -E '^@|^\*|^[0-9]' | sort -n -k2 -k1

Output for the example above will be:

@reboot start_sidekiq
30 * * * * plop
1 0 * * * foo
5 8 * * * bar
23 8 * * * baz

If you want to sort by day (k3), month (k4), or weekday (k5), add the necessary switches accordingly.
If your crontab uses tabs, add -t$'\t' to sort's parameters.

Note that columns with multiple values (e.g. 6,12,18,0 for hours) will be sorted by the 1st number.

Posted by Arne Hartherz to makandra dev (2017-03-14 16:12)