Grimnes


Think. Create. Reiterate

Auto update MacPorts

This method will use Bash scripting and requires sudo. Setting up MacPorts to automagically update on your Mac requires some technical experience, but I will provide you all the necessary information and files.

How to

We will be using a simple Bash script to automatically update our installed MacPorts. The script will create a log file and store the outputs from the update command.

The code provided below should be saved in a Bash file and will be executed as a cron job. Note that you have to define the variable LOG_DEST according to where you wish to store the update log.

Next up, we have to create a cron job to actually perform the update. Open Terminal and open the cron editor by executing:

$ sudo crontab -e

Create a new line and append the following line. Note that you should replace the word path with the absolute path to where you saved the update script.

30 2 * * * path # path := absolute path to where you stored the script

This will update you MacPorts installation each night at 2:30am.

The update script

PORT_EXEC="/opt/local/bin/port"
LOG_DEST="/Users/[username]/Desktop/MacPorts_log.txt"
LINE="############################################################"

rm $LOG_DEST 2>/dev/null # remove the old log file

#
# This script will update MacPorts and its installed ports
# and write a log to the given destination.
#

log () {
    if [[ -n $1 ]]
    then
        # this is passed as an argument
        echo "$1" >>$LOG_DEST # write to log
        echo $1 # write to stdout
    else
        # this is piped
        while read x
        do
           printf "   $x\n" >>$LOG_DEST # write to log
           printf "   $x\n" # write to stdout
        done;
    fi;
}

log "$LINE\n## Update MacPorts ($(date "+%D"))\n$LINE"

log "\nSelf-update MacPorts:" 
$PORT_EXEC selfupdate | log; wait


if [ $($PORT_EXEC list outdated | wc -l) -gt 0 ]; then 
	log "\nOutdated ports:"
	$PORT_EXEC list outdated | log; wait
	
	log "\nUpgrade installed ports:"
	nice $PORT_EXEC -uc upgrade outdated | log; wait
    # -u: uninstall inactive ports when upgrading
    # -c: autoclean after install
else 
	log '\nThe installed ports are up to date.'
fi;

#fix permissions
chmod 775 $LOG_DEST 

Google