Automatically run a task every two weeks without cron

I use fish as my go-to shell – it’s fast, the syntax is more sane than bash, and there are a lot of great plugins for it.

One plugin I use a lot is jethrokuan’s port of z, which allows for very quick directory jumping.

Unfortunately, sometimes I reorganize my directories, and z can get confused and try to jump into a no longer existent directory.

No worries! z thought of that, and provides the z --clean command which removes nonexistent directories from its lists.

But I never remember to run that. Wouldn’t it be nice if I could just have that run automatically every two weeks or so?

Schedule it

I could probably put it in a cron job, but then I’d have to worry about running it inside fish with my local environment, and that’s kind of not what cron is about.

Instead, I decided to stick it at the bottom of my fish.config file, with the following neat trick:

# cleanup z every two weeks
if type -q z
    if test -z "$Z_LAST_CLEANUP"
        set -U Z_LAST_CLEANUP (date +%s)
    # 604800 seconds = 2 weeks
    test (math (date +%s)" - $Z_LAST_CLEANUP") -gt 604800; and z --clean; and set -U Z_LAST_CLEANUP (date +%s)

Some explanation:

if type -q z: we only run this code block if z exists

if test -z "$Z_LAST_CLEANUP": this block checks to see if the Z_LAST_CLEANUP variable is set. If it’s not, then we create a universal variable (which will persist across shell restarts) and set it to our current date/time

date +%s returns the time in # of seconds since the Unix epoch

test (math... checks to see if our current time is more than two weeks since the last cleanup, and if it is, runs z --clean and updates Z_LAST_CLEANUP.

This same technique can be used for any other task you want to run periodically – just figure out the number of seconds in the period you want, update your command/variable, and you’re good to go!


As an exercise for the reader, you could probably turn the above into a relatively simple fisher plugin. Let me know if you do!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.