apt generally requires root permissions, and so you should put this in the
root crontab instead of a
user crontab. On RPi, you can actually get away with using
sudo in a
user crontab as long as the user is pi, but this may not work on many other distributions - it's not a good practice.
Instead, use this:
sudo crontab -e
This will open the
root crontab for editing, and you can enter something like this which will run
apt-get update and
apt-get upgrade once per day at 12:00 noon, and write all of the results to the file
* 12 * * * apt-get update && sudo apt-get -y upgrade >> /home/pi/upgrade_results.log 2>&1
man apt-get to get the latest information for your system, and all of the important details re use of this command.
-y option is needed for
update as it does not generally prompt the user.
>> redirect appends output to the log file; if you want only the results of the most recent run, replace the append redirect with the overwrite redirect:
2>&1 redirect combines the normal
1) output with any
2) error messages; this is the same output you would get in your terminal if you ran these commands from the command line of your interactive shell.
see the crontab guru for help structuring your schedule.
When you test this
cron job, you should not run it at 1 minute intervals because that may not be sufficient time to run both commands to completion. IOW, you're running these commands "on top of each other" with potentially harmful effect. If you feel the need to run this repeatedly for testing purposes, you should run the commands "manually" first, and then use the
--dry-run option in your
cron job. Once you are satisfied the
cron job is working, be sure to remove the
--dry-run option from the
upgrade can generate a fair amount of output, and if you use the append redirect
>>, your log file will become large over time. You should review it regularly, and either trim or simply delete the file. If you want to constrain the size of your log automatically, consider the
logrotate command, or perhaps another
cron job that pipes the log file through
tail with the
-c option to a temporary location & overwrites the log file with the tmp file.