How to show an ordered crontab

Posted . Visible to the public.

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

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.

Arne Hartherz
Last edit
Arne Hartherz
Keywords
visualize, render
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2017-03-14 15:12)