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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)