Search code examples
bashcron

How to match regex in crontab


I got a problem with crontab. I need to check the date to execute a script.

I want to run the command [[ $(date '+%a') =~ Thu|jeu ]] && echo 'aaaaaaa'. This wroks perfectly on the terminal. But if I put it in crontab : [[ $(date '+\%a') =~ Thu|jeu ]] && echo 'aaaaaaa' it didn't work.

In the /var/log/syslog I got : CRON[5461]: (root) CMD ([[ $(date '+%a') =~ Thu|jeu ]] && echo 'aaaaaaa' > /tmp/z.txt 2>&1)

Did someone know why the command work on terminal but not on the cron ?


Solution

  • Crontab default to POSIX sh and you're using a bash specific syntax.

    The obvious solution is to set your shell in the crontab entry itself. and cron also has a limited set of PATH.

    SHELL=/bin/bash
    
    [[ $(/bin/date '+\%a') =~ Thu|jeu ]] && echo 'aaaaaaa'
    

    Or just use POSIX sh syntax

    case "$(/bin/date '+\%a')" in Thu|jeu) echo 'aaaaaaa';; esac
    
    • Assuming date is really in /bin/date otherwise you will need to set the PATH as well in the crontab entry so you can just do date in the crontab.

    • See man 5 crontab