Saturday, February 26, 2022

[SOLVED] is it possible to truncate my existing crontab file with a bash script?

Issue

Part of my application deployment pipeline on AWS includes a bash script that updates the hosts CRON file, in addition to running a ruby install as the user

sudo -u myuser bash << eof
  echo 'running bundle install'
/home/myuser/.rvm/gems/ruby-2.4.1/wrappers/bundle install
  echo 'install cron tasks'
  (crontab -l 2>/dev/null; echo "TZ=America/Los_Angeles")| crontab -
  (crontab -l 2>/dev/null; echo "CRON_TZ=America/Los_Angeles")| crontab -
  (crontab -l 2>/dev/null; echo "00 13 * * * /bin/bash /var/www/application/bin/daily-notifications.sh")| crontab -
  crontab -l
eof

unfortunately In order to update my AMI image I need to first manually go into my crontab file and erase the cron tasks first prior to taking a new image of the OS, because the code above is "appends" each line to the end of the existing file

is it possible in the bash script above to purge the cron tasks programmatically?


Solution

Yes, per the crontab manpage:

SYNOPSIS
       crontab [ -u user ] file
       crontab [ -u user ] [ -i ] { -e | -l | -r }

DESCRIPTION
[...]
       The -r option causes the current crontab to be removed.

So you would use the command crontab -r



Answered By - Nick ODell
Answer Checked By - Marilyn (WPSolving Volunteer)