zvxr
zvxr

Reputation: 187

Bash Script - how to get script directory so that it runs in Cron

I've been working on a script that is to be run from a couple different locations/servers (all checked out from svn). To get the script's directory (used for generating files in the directory), I have been using this:

script_dir="$( cd "$( dirname "$0" )" && pwd )"

This works great, but does not seem to execute in crontab. I have made sure that there are no relative paths used in the script, and this script works through crontab when substituting $script_dir with the directory's path.

Any thoughts?

Upvotes: 1

Views: 4320

Answers (2)

estani
estani

Reputation: 26487

Just to give it a though, are you sure that line is not working? Debugging cronjobs is pretty tricky.

crontab uses the sh shell unless you change it, if you have anything from another shell, say command redirection from bash, it won't work.

Try executing the script with sh and an empty environment:

env - sh <script>

I think this is the closest you can get to mimicking the crontab behavior. But paths are the first problem, so be sure to put absolute paths there.

Upvotes: 1

Gordon Davisson
Gordon Davisson

Reputation: 125828

dirname is probably not in the default PATH for cron jobs. I don't know about your system, but on OS X dirname is in /usr/bin, which isn't in cron's default PATH. If this is the problem, there are 3 easy ways to fix this:

  1. Give the full path to the dirname command (and other commands you use in the script): script_dir="$( cd "$( /usr/bin/dirname "$0" )" && pwd )"
  2. Explicitly set the PATH at the beginning of the script: PATH=/usr/bin:/bin:/usr/sbin:/sbin (or something like that)
  3. Explicitly set the PATH in your crontab file: PATH=/usr/bin:/bin:/usr/sbin:/sbin (make sure this line is before the entry that runs your script)

Upvotes: 2

Related Questions