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 /home/pi/upgrade_results.log
:
* 12 * * * apt-get update && sudo apt-get -y upgrade >> /home/pi/upgrade_results.log 2>&1
Please review man apt-get
to get the latest information for your system, and all of the important details re use of this command.
No -y
option is needed for update
as it does not generally prompt the user.
The >>
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: >
The 2>&1
redirect combines the normal stdout
(1
) output with any stderr
(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 -s
or --dry-run
option in your cron
job. Once you are satisfied the cron
job is working, be sure to remove the -s
or --dry-run
option from the apt-get
command.
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.
/etc/crontab
as it contains the user column.* * * * *
, the above1 * * * *
runs ever hour at minute 1, so 8:01AM, 9:01AM.. etc