简体   繁体   中英

Issue with scheduling a bash script with crontab

Using:

20 21 * * *  /bin/sh /Users/username/Documents/first.sh

to execute my script which does btw have this at the top:

#!/bin/sh

and instead I am getting this:

You have new mail in /var/mail/username

with the following output:

/Users/username/Documents/first.sh: line 3: wget: command not found
/Users/username/Documents/first.sh: line 4: wget: command not found

How do I fix this?

Even though you made your cron job work somehow, I'd really like to point out that your "solution" seems irrelevant.

  1. "bash first.sh" is not a good idea since the beginning of the script starts with "#!/bin/sh", which means: you simply "first.sh" and the system will interpret it using "/bin/sh".

  2. "cd /Users/username/Documents" does NOT solve the "command not found" issue.

This is actually a common issue with cron jobs. The root cause is: the cron jobs (first.sh in this case) run in a "clean" environment. That is, your profile is not sourced. Consequently, the PATH env var contains only a minimal number of path and unfortunately the "wget" is not in those paths.

Solution: it is simple and straight forward. You can

  1. evoke wget etc. with their absolute paths. Or
  2. setup PATH accordingly (or source in corresponding profiles) at the beginning of you script.

For the sake of security, we usually prefer to call external commands (wget etc.) using absolute paths.

Thank-you everyone, I have found a solution:

I modified my crontab file:

34 21 * * * cd /Users/username/Documents && bash first.sh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM