Posts: 28
Joined: Sat Oct 11, 2014 1:42 pm

update script

Sat Oct 11, 2014 1:47 pm

Hey all!

I was wondering if anyone could help me learn by showing me exactly how to make a script that would run each time a certain time comes up for the system.

what I would like to accomplish is to make a script that runs each day at 3am that does
sudo apt-get update && sudo apt-get upgrade (and automatically accept any updates, dont know how or if its possible)
sudo rpi-update (and catch if theres any errors somehow, if its possible)
and reboot

asking since I am new to linux but I want this function but also want to learn how to make it work the way I want it to :P

your sincerely Natherul

User avatar
Posts: 20212
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: update script

Sat Oct 11, 2014 6:06 pm

The scheduling is easy. "cron" is the thing that handles that for you.

"cron" is a daemon (system program) that runs user programs according to a schedule that you set up. The schedules are store in a "crontab" for each user (and a special one for the system). You can edit your crontab with "crontab -e".

To run a script at 3am every day you would need to add a line like

Code: Select all

0 3 * * * /home/pi/myscriptname 2>&1 >/home/pi/myscriptoutput
The fields are all described in the crontab manual page "man 5 crontab". I'll summarise them briefly in order.
1: Minute past the Hour to run the command on. As you want to run at 3:00, this is 0.
2: Hour of the Day. Obviously this is 3 for 3am.
3: Day of the month. Putting * means run every day.
4: Month of the Year. Again, * for every month.
5: Day of the Week. Every weekday is *.
Everything after that is the command(s) to run.
I've redirected the output of the command to a file so you can check for errors.
Change "myscriptname" and "myscriptoutput" to names to suit you :)

Now the script. Just for starters, something like

Code: Select all

#!/bin/bash -e

# First do apt-get update
/usr/bin/sudo apt-get update

# Then the upgrade
/usr/bin/sudo apt-get -y upgrade

# Finally rpi-update
/usr/bin/sudo rpi-update

# Trigger a reboot
/usr/bin/sudo shutdown -r
The "#!/bin/bash -e" Says to use the bash interpreter and stop if any errors occur.
I've put "/usr/bin/sudo" instead of just "sudo" as the PATH used by cron isn't the same as that used at the command line.

The "-y" on apt-get upgrade means to assume "yes" answers to any questions.

Ask if you're not sure of any bits there and don't forget the "man" command is your friend :)

Posts: 28
Joined: Sat Oct 11, 2014 1:42 pm

Re: update script

Sat Oct 11, 2014 8:20 pm

cheers mate, added it now. Hope to see it working (but I wont since I will be asleep) :P

Return to “Raspberry Pi OS”