Schedule Crontab task by script.sh

Asked

Viewed 284 times

3

I want to schedule the crontab through a script.sh.

I tried to add the following line inside the script.sh:

echo "00 01  * * *  retag    /retag/licenca.sh" >> /etc/crontab

It worked, but he adds a line each time the script runs. I need him to book one time and only.

How to solve this?

I need to schedule this file in many places and at the same time, so the question, wanted a way to expedite the process.

  • With the >> it adds the output of the command at the end of the file. With the > it rewrites the file only with the output content of the command.

  • but then it erases everything I already have scheduled correctly? I need to put at the end of the file without replacing what already has!

  • the end will always be retag /retag/licenca.sh? From what I understand you need that when you run the script if there is this line it only changes the schedule time and the rest of the /etc/crontab remain intact, would that?

  • Yes, the end will always be retag /retag/licenca.sh ! I wouldn’t want the script to insert that line inside the crontab the first time it runs, the second time the script runs, if it already has that line inside it does nothing!

  • The way I said it in the question it’s working, but every time the script runs it adds this line again! That is, if I schedule it to run once a day for 30 days it will generate 30 lines within the crontab!

  • sed -i 's/.*retag \/retag\/licenca.sh/30 13 * * * retag \/retag\/licenca.sh/' /temp/crontab does a test with this command... only changes the path to the file at the end, I copied the crontab to another directory to test

Show 1 more comment

2 answers

1

A simpler option is to use sed at the beginning of your script, it will delete the existing lines in your crontab, and as soon as it runs the licenca.sh with the echo, a new line will be created in place.

sed '1d' /etc/crontab
echo "0 1  * * *  retag /retag/licenca.sh" >> /etc/crontab

In charge sed 1 is referenced to the first line of the file, the d serves to delete this line, always in single quotes.

If you want to know more about the command, use the documentation.

0

Do a simple test before, like,:

grep -q licenca.sh /etc/crontab || echo "00 01 * * *  retag    /retag/licenca.sh" >> /etc/crontab

If you do not find the string "licenca.sh" in the file, add. If it does, it does nothing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.