Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm managing multiple machines running Debian, Raspian, and Mint. On some of the machines I want to have updating and upgrading automatically. I've drafted a script that I want to do this and log if the update are successful or not.

#!/bin/bash

captains_log=/home/jason/mission_control/captains.log

apt-get update;
if [ $? == 0 ]; then
    apt-get upgrade -y;
    if [ $? == 1 ]; then
        echo `date`": Daily update failed" >> $captains_log
    else
        echo `date`": Daily update successful" >> $captains_log
    fi
else
    echo `date`": Daily update failed" >> $captains_log
fi

I've set the script to run @daily in a root crontab. I run the command manually and it executes as desired. When cron runs the script, I get success in the log but my software is not getting updated.

Can someone tell me where I'm going wrong?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

The recommended way to do this is using the unattended-upgrades command. Setting it up is simple:

apt-get install unattended-upgrades
dpkg-reconfigure unattended-upgrades

This is all you need to get the results of what you intend in your cron script. There is no need to reinvent the wheel.

As far as your script and it's report of success, any non-zero return code is considered a failure. Your script considers any non-1 to be success. There is no need to check exit codes manually, that is what if does.

if apt-get upgrade -y; then
    echo "$(date): Daily update successful" >> $captains_log
else
    echo "$(date): Daily update failed" >> $captains_log
fi

When the shell has a "command not found", an exit code of 127 is returned.

share|improve this answer
1  
Thanks jordanm. Your answer not only helped me to find a better way to accomplish my goal, I have a better understanding of exit codes and how to use them. I set up unattend-upgrades, which runs daily via cron and logs to /var/log/unattended-upgrades.log. –  not__p May 31 '13 at 22:31

Is apt-get in the crons shell-searchpath?

It is always good practice to use the full path to external commands in cron-jobs.

share|improve this answer
    
Good point, but wouldn't the log show that the script failed? –  not__p May 31 '13 at 21:12
    
@Jason Yes, it should in your case. In more difficult scenarios this is harder to spot, though. –  Nils Jun 1 '13 at 19:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.