1

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?

0

2 Answers 2

1

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).

1
  • thank you, this is easier. I tried before a much similar method but it did overwrite the other crontab
    – Virgula
    Commented Oct 31, 2020 at 19:40
0

Solved. Crontab needs \n at the end of the latest line to execute commands:

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

if [[ $value = 0 ]];
then
    printf "$var\n$script\n" | crontab;
else
    printf "$script \n" | crontab;
fi
1
  • Embedding arbitrary strings (like the old crontab contents) in a printf control string is not safe. Use something like printf '%s\n' "$var" "$script" instead. Commented Oct 31, 2020 at 20:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .