Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

linux - How to run a Shell Script by Cron Job

I have a Shell script like below

 echo "Hello World"

The script is located in /root/scripts/ folder as test.sh

I also created a cron job like below

  0-59 * * * *  ./scripts/test.sh

Now the cron job is not printing the content in test.sh every minute.

Let me know whether I have given a wrong directory or I have any other problem in my code.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I would

  1. Be explicit wrt. your directory to execute from e.g. /root/scripts/test.sh. I don't know what cron would regard as the current directory
  2. Redirect stdout to a log file e.g. ...test.sh > /tmp/cron.log (you would likely want to redirect stderr at some stage too using 2>&1). Otherwise you're not going to see the output. It gets mailed to the cronjob owner
  3. Make sure you've given execution permission to your bash script (chmod +x /root/scripts/test.sh)
  4. Be explicit which script executable will execute your shell script. It's good practise to have a script invocation at the top e.g. #!/bin/sh or similar

Getting stuff to run under cron is notoriously tricky. Cron jobs run with a massively cut-down environment. It's instructive to print out the environment available to your script (use env) and compare/contrast with what you have available from your interactive shell.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...