What is the 'working directory' when cron executes a job?

  • I have a script that works when I run it from the command line, but when I schedule it with cron I get errors that it cannot find files or commands. My question is twofold:

    1. When I schedule a cron job using crontab -e, does it use my user ID as the basis for its permissions? Or does it use a cron user ID of some sort and its related permissions?

    2. When a cron job is launched, what is the working directory? Is it the directory where I specify the script to run, or a different directory?

    Here is my cron job:

    15 7 * * * /home/xxxx/Documents/Scripts/email_ip_script.sh
    

    Here is the actual script:

    vIP_ADDR="`curl automation.whatismyip.com/n09230945.asp`"
    echo "$vIP_ADDR"
    sed "s/IPADDR/$vIP_ADDR/g" template.txt > emailmsg.txt
    ssmtp [email protected] < emailmsg.txt
    

    Here are the errors I get when I view the mail message produced by cron:

    sed: can't read template.txt: No such file or directory
    /home/xxxx/Documents/Scripts/email_ip_script.sh: line 15: ssmtp: command not found
    

    It cannot find the template.txt but it resides in the same directory as the script. It also cannot run ssmtp, but I can as my user. What am I missing to get this to work properly?

  • Add cd /home/xxxx/Documents/Scripts/ if you want your job to run in that directory. There's no reason why cron would change to that particular directory. Cron runs your commands in your home directory.

    As for ssmtp, it might not be in your default PATH. Cron's default path is implementation-dependent, so check your man page, but in all likelihood ssmtp is in /usr/sbin which is not in your default PATH, only root's.

    PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin
    15 7 * * * cd /home/xxxx/Documents/Scripts && ./email_ip_script.sh
    

    @Giles - Thanks, would `cron` have it's own `PATH` or can I check my user's `PATH`? I set ssmtp up to have it's own `user` and `wheel` permission thinking it would allow anyone to use it (including cron). If it helps Im on CENTOS 6.2

    @ProfessionalAmateur Your problem isn't that you aren't allowed to use `ssmtp`, but that your cron job doesn't find any executable called `ssmtp` because it's not in your `PATH`. There's no such thing as “your user's `PATH`”; this is a per-process setting, not a per-user setting. You can set the path for all your cron jobs by putting a `PATH=…` line in your crontab.

    I had to add MAILTO='[email protected]' as well to get it working along with PATH setup. Wierd but it worked for me.

    For ssmtp one can use; `´which ssmtp´ ...`

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM