Script doesn't run via crontab but works fine standalone

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
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
#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

#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
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


The problem was solved read the manual in Google:

description:

  1. I have script using #!/bin/bash as header
  2. I put the script on /home/wc3/palert/

analysis:

  1. crontab can't run my script
  2. But if I run manually it show the output and also I can see the result on my web
  3. It means crontab can't get the environment not like when you run your script on your script folder

answer:

  1. put your environment using this line below on your script with:

    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/wc3/palert
    

    change this: /home/wc3/palert
    with: the place that you put your script e.g. /home/budi/script.sh

sample:

#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/budi
# Script continues...

Try put your script on crontab.

Tags:

Cron