The script runs from command line but crontab fails

后端 未结 3 1236
情歌与酒
情歌与酒 2021-01-24 11:21

I\'m still learning Bash and I\'m having a problem with my script. I want to filter some calls with this script that is analyzing a call log, every 2 minutes as cronjob. The pro

3条回答
  •  渐次进展
    2021-01-24 12:03

    Your script assumes that it is being run from a particular directory (note that almost every path is a relative path, not an absolute path). cron happens to be running it from another directory.

    The Fix

    If the script works when you run it from the directory it lives in, add the following to the top of your script:

    mydir=$(dirname "$0") && cd "${mydir}" || exit 1
    

    Explanation

    $0 is the (possibly relative) filename of the shell script being executed. Given a filename, the dirname command returns the directory containing the filename.

    So, that line changes directories to the directory containing the script or exits with an error code if either dirname or cd fails.

提交回复
热议问题