Automating Homebrew Upgrade with Cron

Today I was investigating how to run cron jobs on my mac laptop. I wanted to automate the upgrade of my homebrew packages.

The process is extremely easy.

First run crontab -e and press enter.

Inside this file you place your bash commands with a little trick.

The jobs are stored in the following format

[minute] [hour] [day_of_month] [month] [day_of_week] [user] [command_to_run]

So to run our bash command every day we use 0 0 * * * followed by the desired command.

First we need to write the bash script.

#!/bin/bash
/usr/local/bin/brew upgrade

This runs the command brew upgrade. The reason we need /usr/local/bin/brew is because when a cron job runs, it doesn’t have your PATH defined so commands like brew won’t work. We need to specify the exact directory to be able to run them.

Next we need to make this script executable.

chmod +x b_up.sh

Now we can setup the cron job.

My job looks like this

0 0 * * *  cd Documents && ./b_up.sh >> b_log.txt 2>&1

So every day we first cd to the Documents folder and run the b_up.sh script. The output is appended to the b_log.txt file.

The 2>&1 command means that we don’t get mail about this job.

One problem I ran into here was that cron didn’t have sufficient permissions to run.

What I needed to do to fix this was to add cron into my Full Disk Access in the settings of my mac. A tutorial to do so can be found here

Now my cron job is working perfectly!

One improvement to this process would be to first check if there are any updates before running brew update as this does waste unnecessary resources.

Until next time.