Ubuntu – Script doesn’t run via crontab but works fine standalone


I have a script that reminds me to restart my computer if uptime is more than, say 3 days (although its set to 0 days now just to check if the script is running as my computer has been up only over a day..).

I realize it isn't the most elegant script but I am trying! :)


up=$(uptime | grep "day" > /home/username/uptime.foo && awk < /home/username/uptime.foo '{ print $3 }')

[[ $up -gt 0 ]] && xmessage -center "Restart!"

I have made it executable by chmod + x checkup.sh and it works fine when I run it fro the terminal via ./checkup.sh

My crontab entry for this script is:

46 14 * * * /home/username/Desktop/./checkup.sh

So it runs at 14:46hrs daily…

So… I am thinking it should run, unless I didn't something really silly.
Also, do you think it's ok to move this bash script to /bin?

Best Answer

One thing at a time:

First let's give you a user based bin folder:

cd ~/ && mkdir bin

You want to use crontab. Let's start with something really simple:

* * * * * touch /tmp/testing.txt

Okay, so that works

Now let's try running a script that does the same

* * * * * /home/username/bin/touchtest.sh

to run once a minute until you get it working
No you don't need a ./ in the middle of the line. ./ is for when you are giving relative urls.
Okay, so that works

Now let's try running a script that calls xmessage

* * * * * /home/username/bin/rebootwarn.sh

not working

First we need to not depend on environment variables. This includes path setting, x11 settings, or anything else(python and ruby environment variables come to mind...)

Let's make ours look a bit like anacron's proper cron file..I saved this as test

#Borrowed from anacron
#End borrowed from anacron

* * * * *   /bin/bash /home/username/bin/test.sh

Set to run once a minute

crontab test to import it

On to the script

export DISPLAY=:0.0
up=$(uptime | grep "day" > /home/dnaneet/uptime.foo && awk < /home/dnaneet/uptime.foo '{ print $3 }')

[[ $up -gt 0 ]] && xmessage -center "Restart!"`

Okay, so that works...what did we do?
We changed all the commands not to depend on paths we didn't explicitly set
We ran our script explicitly with bash
We told the script that we expect to be on DISPLAY :0.0

Related Question