Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

bash - Running a simple shell script as a cronjob

I have a very simple shell script I need to run as a cronjob but I can't get even the test scripts to run. Here's and example script:

/home/myUser/scripts/test.sh

#!/bin/bash
touch file.txt

crontab:

* * * * * /home/myUser/scripts/test.sh

The script runs fine from the terminal but can't get it to run as a cronjob. So far I've tried these in crontab:

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

* * * * * /bin/bash /home/myUser/scripts/test.sh

And this in the the script file:

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/myUser/scripts

From what I've gathered the solution might be in the PATH variable but I can't figure out what it is since my understanding is very limited at this point. So my question is, how do I get my scripts to run as cronjobs?

EDIT: the file has rwx permissions for all users. This is just for testing purposes.

EDIT: cronjobs such as * * * * * touch /home/myUser/scripts/test.txt work but it wont run scripts.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The easiest way would be to use a GUI:

For Gnome use gnome-schedule (universe)

sudo apt-get install gnome-schedule 

For KDE use kde-config-cron

It should be pre installed on Kubuntu

But if you use a headless linux or don′t want GUI′s you may use:

crontab -e

If you type it into Terminal you′ll get a table.
You have to insert your cronjobs now.
Format a job like this:

*     *     *     *     *  YOURCOMMAND
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- Day in Week (0 to 7) (Sunday is 0 and 7)
|     |     |     +------- Month (1 to 12)
|     |     +--------- Day in Month (1 to 31)
|     +----------- Hour (0 to 23)
+------------- Minute (0 to 59)

There are some shorts, too (if you don′t want the *):

@reboot --> only once at startup
@daily ---> once a day
@midnight --> once a day at midnight
@hourly --> once a hour
@weekly --> once a week
@monthly --> once a month
@annually --> once a year
@yearly --> once a year

If you want to use the shorts as cron (because they don′t work or so):

@daily --> 0 0 * * *
@midnight --> 0 0 * * *
@hourly --> 0 * * * *
@weekly --> 0 0 * * 0
@monthly --> 0 0 1 * *
@annually --> 0 0 1 1 *
@yearly --> 0 0 1 1 *

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...