Crontab, which stands for cron table, is used to run one or more scripts in Linux based on a specific time. Usually, if you want to change something in the crontab, you use the crontab -e command and then change the crontab. But I want to change crontab using a shell script.
Problem
How to change crontab using a bash script?
Solution
I create a bash script to execute something on my Linux server, and in my script, I want to change the crontab so the script will add, change, or remove the script in the crontab. Here are ways to change crontab using a script:
1. Add a script in crontab
For example, if you want to add a random.sh script which is in the /root/scripts folder in crontab and will run every 5 minutes, then use the command below:
(crontab -l 2>/dev/null || true; echo "*/5 * * * * /root/scripts/random.sh") | crontab -

Or if you want to add the script to the crontab in another form of writing, then you can use the command below:
(crontab -l 2>/dev/null || true; echo "*/5 * * * * cd /root/scripts;./random.sh") | crontab -

2. Change the script in crontab
If you want to change the file in crontab to once every 10 minutes (previously every 5 minutes) for the random.sh script in the /root/scripts folder, then use the command below:
crontab -l | sed 's/\*\/5 \* \* \* \* \/root\/scripts\/random.sh/\*\/10 \* \* \* \* \/root\/scripts\/random.sh/g' | crontab -

Or, you can execute the command below if your script uses another form of writing in crontab:
crontab -l | sed 's/\*\/5 \* \* \* \* cd\ \/root\/scripts\;\.\/random.sh/\*\/10 \* \* \* \* cd\ \/root\/scripts\;\.\/random.sh/g' | crontab -

3. Disable and enable the script
If you want to disable the random.sh script in crontab, then use the command below:
crontab -l | sed 's/\*\/10 \* \* \* \* cd\ \/root\/scripts\;\.\/random.sh/\#\*\/10 \* \* \* \* cd\ \/root\/scripts\;\.\/random.sh/g' | crontab -

But if you want to enable it, use the command below:
crontab -l | sed 's/\#\*\/10 \* \* \* \* cd\ \/root\/scripts\;\.\/random.sh/\*\/10 \* \* \* \* cd\ \/root\/scripts\;\.\/random.sh/g' | crontab -

4. Deleting the script in crontab
Use the command below if you want to delete the random.sh file in crontab:
crontab -l | sed '/\*\/5 \* \* \* \* \/root\/scripts\/random.sh/d' | crontab -

Or, you can execute the command below if your script uses another form of writing in crontab:
crontab -l | sed '/\*\/5 \* \* \* \* cd\ \/root\/scripts\;\.\/random.sh/d' | crontab -

Note
You have to pay attention to whether the script in the crontab uses spaces or tabs because it greatly affects whether the script that you run can change something in the crontab or not. You have to put a backslash(\) if you want to change or delete your script in crontab that uses symbols like an asterisk(*), forward slash(/), hash(#), space, and so on.
References
techtarget.com
stackoverflow.com
webopedia.com

