MacOS – Cronjob macOS does not work if set with a bash external script

bashcatalinacronmacos

I'm trying to create a new cronjob which launches a script every time at startup. If I do cronjob -e and then I insert for example @reboot bash /Users/user/script.sh and then I save everything is fine:

crontab: no crontab for user - using an empty one
crontab: installing new crontab

If I reboot my mac the script gets executed successfully. What I'm attempting to do is to create a cronjob with a bash script just like this:

var=$(crontab -l 2> /dev/null);
value=$(echo $?);
script='@reboot bash /Users/user/myscript.sh';

if [[ $value = 0 ]];
then
    printf "$var \n$script" |crontab -;
else
    printf "$script" | crontab -;
fi

It seems to work because if I do crontab -l I find my script @reboot bash /Users/user/myscript.sh but after restarting the Mac, the script does not get executed. Any ideas why it is not working, and how can I get it to run?

Best Answer

There is no need to check whether there currently is a crontab installed or not. Just run

(crontab -l 2>/dev/null; echo '@reboot bash /Users/user/myscript.sh') | crontab -

to add the @reboot line to your crontab (or create a new one).