Ubuntu – script does not write to file when executed from cron

14.04bashcronscripts

When I run a /bin/bash script, it works fine and it logs into some log files inside the script. But, when I run it from cron, it does not log to the file! it only logs to /var/mail/root , saying that

Date: Fri, 12 Aug 2016 08:39:01 +0300 (MSK)

/bin/sh: 1: root: not found

this is the script:

#!/bin/bash

LOG_FILE="test-crontab.log"
echo "started testing cron" >> ${LOG_FILE}

pgrep tunnel
if [[ ${?} != 0 ]]; then
  echo "Tunnel process is not running..." | tee -a ${LOG_FILE}
  echo "initializing tunnel..." | tee -a ${LOG_FILE}
  /usr/local/bin/stunnel | tee -a ${LOG_FILE} 2>&1
fi

echo `date` >> ${LOG_FILE}

and this is the cron:

45 8 * * *  /home/ubuntu/sam/scripts/sqlplus-scripts/accts-ct/test-crontab.sh > /dev/null

Best Answer

  1. To get the log file where you expect it to be, replace:

    LOG_FILE="test-crontab.log"
    

    With:

    LOG_FILE="/home/ubuntu/sam/scripts/sqlplus-scripts/accts-ct/test-crontab.log"
    
  2. The command [[ ${?} != 0 ]] is bash-only. From the error message that you quote, the script appears to be running under /bin/sh. One way to fix that is to replace:

    if [[ ${?} != 0 ]]; then
    

    With:

    if [ ${?} != 0 ]; then
    

    Another approach is to run crontab -e and add the following line to your crontab file:

    SHELL=/bin/bash
    
  3. Also, for simplicity and style, consider replacing:

    echo `date` >> ${LOG_FILE}
    

    with:

    date >> "${LOG_FILE}"
    

    This eliminates a useless use of echo.

  4. Lastly, consider putting double-quotes around all shell variables, particularly $LOG_FILE. Because the current value of LOG_FILE contains no spaces or shell-active characters, this is not needed now. But, putting double-quotes around them will will prevent unpleasant surprises in the future.

Related Question