2021-07-19 Sorting crontab chronologically

On one of the computers I work on there is a pretty extensive crontab file, with many tasks carefully scheduled so that they run every day in a specific order. No wonder I would like to be able to sort all the crontab entries chronologically, i.e., in the order of the time they should be called. (I don’t care about the dates, since most of these tasks are scheduled to run every day.) The problem is that (for some mysterious reason) the crontab file format requires putting the minutes first and the hours next.

Luckily, sort can sort by fields (by default separated by whitespace). So, here’s a simple way to sort crontab entries chronologically. Notice how the grep invocation removes blank lines. (Actually, it removes more – it only leaves lines beginning with a digit, which is fine, since an asterisk in the “minutes” position wouldn’t be useful with sorting anyway. It doesn’t remove lines where the hours field is an asterisk, though, and hence isn’t fully correct – but since it’s a quick-and-dirty solution, I’m fine with that.)

crontab -l | grep '^[0-9*]' | sort -k 2g,1g

That’s it for today!

CategoryEnglish, CategoryBlog