0

Hey guys I'm really new to linux and still learning so hopefully this will be an easy one for you guys.

I'm trying to learn more about how to use cron to schedule events on my ubuntu machine. Right now I have a script (script.sh) that is as follows:

#!/bin/bash

echo "I work" 

I log into terminal as root (sudo -i) and am entering:

sudo bash /home/lskidson/tests/script.sh 

It properly executes the script when I do this. (Still logged on as root) I have a crontab set up to execute this script every minute that I can not get to work it is as follows (I set it up using crontab -e)

* * * * * sudo bash /home/lskidson/tests/script.sh

I write it to the file then when I print the job list (crontab -l) it appears properly as I have asked it to. However, the script never runs.

Do you guys have any general tips as to what could be wrong? I can provide more info if needed. Thanks in advance!

1

How do you know it never runs? It is not going to echo to your terminal. First drop the sudo...that should never be in a cronjob. A crontab for root runs as root, the crontab for a user runs as the user, place your script accordingly.

Pipe your output to file like so

echo "I work" > /path/to/some/file.txt

or

* * * * * /home/lskidson/tests/script.sh > /path/to/some/file.txt

Use > to overwrite the file, >> to append to it.

1

Firs with the shebang #!/bin/bash you already defined this is a Bash script. Next step is to create the file executable to run it without the command bash in from of it:

chmod +x /home/lskidson/tests/script.sh 

In general the command sudo is not applicable within crontab. If you need to run Cronjob by root you can use the root's crontab, that can be achieved by the command sudo crontab -e.

Now we can go to the Crontab's question. Where you expect to receive the message "I work"? There are few cases.

1. If the executable file generates an output file, or just modifies some things, the Cron job should be:

* * * * * /home/lskidson/tests/script.sh 

2. If the program doesn't write any output file and just generates some data within the stdout (as it is in your case), you should redirect it to a file to see it into an appropriate place (this part 2>&1 redirects and the error messages to stdout):

* * * * * /home/lskidson/tests/script.sh >> /home/lskidson/tests/script.sh.log 2>&1

3. While the stdout isn't redirected, Cron will sending local mails to the user (if your local mail is setup properly), unless this is overridden by setting the variable MAILTO in crontab:

MAILTO="my@custom.mail"
* * * * * /home/lskidson/tests/script.sh

References:

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.