Home > Net >  add bash script to crontab via bash script
add bash script to crontab via bash script

Time:12-18

I would like to add date with filename to my bash script which would be added to crontab file via script. The problem is entry in crontab file is already having the date appended. But my requirement is to have the date command in crontab.

crontab -l > "$FILENAME"
if grep -i cron "$FILENAME"; then
    echo "Cron Job already present in User's crontab file"
else
    echo "*/5 * * * * bash -x /home/cronjob/cron.sh > /home/cronjob/myjob_`date  \%Y\%m\%dT\%H\%M\%S`.log 2>&1 " >> mycron
    crontab mycron
    echo "Crontab added to User's Crontab"
fi

Actual :

*/5 * * * * bash -x /home/cronjob/cron.sh > /home/cronjob/myjob_20211217053830.log 2>&1

Requirement :

*/5 * * * * bash -x /home/cronjob/cron.sh > /home/cronjob/myjob_`date  %Y%m%d%H%M%S`.log 2>&1

I have also tried to add escape characters but didn't seem to work

CodePudding user response:

It looks like your crontab entry is close. Since %'s are special (newline) characters in a crontab file, escaping them should give the desired result:

*/5 * * * * bash -x /home/cronjob/cron.sh > /home/cronjob/myjob_`date  \%Y\%m\%d\%H\%M\%S`.log 2>&1

I verified that this works in Ubuntu.

Additionally, adding the line SHELL=/bin/bash to the crontab file (above the entries) ensures that bash interprets the crontab entries. While you likely will not need it it this case, it would enable more possibilities.

CodePudding user response:

Use cat

cat << '==CRONTAB_LINE==' >> mycron
*/5 * * * * bash -x /home/cronjob/cron.sh > /home/cronjob/myjob_$(date  %Y%m%dT%H%M%S).log 2>&1 
==CRONTAB_LINE==

Result

crontab -e
*/5 * * * * bash -x /home/cronjob/cron.sh > /home/cronjob/myjob_$(date  %Y%m%dT%H%M%S).log 2>&1
  • Related