Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement not working in cron

I have the following code: (record.sh)

cd $(dirname $0)

dt=$(date '+%d/%m/%Y %H:%M:%S');
echo $dt;
read action < /home/nfs/sauger/web/pi/action.txt
echo $action;
if [[ $action == *"start"* ]]
then
  echo "start recording"
  ./gone.sh
  exit 1
elif [[ $action == *"stop"* ]]
then
 echo "stop recording"
  ./gone.sh
  exit 1
else 
#More stuff done here
fi

When I run this script manually the output is the following:

19/01/2016 19:07:11
start
start recording

If the same script is run via a (root) cronjob, the output is the following:

19/01/2016 19:07:01
start

As you can see, the file "action.txt" has been read without a problem ("start" is logged both times) so this should not be an issue of permissions or wrong paths. But when run as a cronjob, the if-statement is not called. No "start recording" appears.

So my question is: Why does the if-statement work when I call the script manually, but not when this is done via cron?

like image 689
Ole Albers Avatar asked Mar 13 '23 13:03

Ole Albers


1 Answers

Your script is written for bash; these errors are almost certainly indicative of it being run with /bin/sh instead.

Either add an appropriate shebang and ensure that it's being called in a way that honors it (/path/to/script rather than sh /path/to/script), or fix it to be compatible. For instance:

case $action in
  *start*)
    echo "start recording"
    ./gone.sh
    exit 1
    ;;
  *stop*)
    echo "stop recording"
    ./gone.sh
    exit 1
    ;;
esac
like image 56
Charles Duffy Avatar answered Mar 20 '23 18:03

Charles Duffy