1

I'm writing a script and I'm wanting to be able to delete a specific job/task that a user can create using the Crontab command.

I know that to be able to simply delete all jobs/tasks, you just use:

crontab -r;

But if there's multiple jobs/tasks how are you able to list them and then delete selected ones?

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93

2 Answers2

2

Use crontab -e, it should open all the cron tasks in the system editor and then you remove the specific entry and save and exit. Cheers

Edit: Adding remove from script

You can do something like -

crontab -l | grep -v '<SPECIFICS OF YOUR SCRIPT HERE>' | crontab -

from your script. Give it a try and let me know if it worked

pinaki
  • 5,393
  • 2
  • 24
  • 32
-1

Display available jobs with indexing, read user choice, delete job by its index

#!/usr/bin/env bash

# Array of cron job entries
typeset -a cron_entries

# Store the contab jobs into an array
mapfile -t cron_entries < <(crontab -l | grep -vE '^(#.*|[[:space:]]*)$')

if (( ${#cron_entries[@]} > 0 )); then

  # List all the jobs
  echo "Here are the current cron jobs:"

  printf 'Index\tJob entry\n'
  for ((i=0; i<"${#cron_entries[@]}"; i++)); do
    printf '%4d\t%s\n' $i "${cron_entries[i]}"
  done

  # Prompt user for job index or exit
  read -p $'\nPlease choose a job index to delete, or an invalid index to abandon: ' -r answer

  # If answer is a positive integer and within array bounds
  if [[ "$answer" =~ ^[0-9]+$ ]] && (( answer < ${#cron_entries[@]} )); then

    # Show deleted entry
    printf '\nDaleting:\t%4d\t%s\n' "$answer" "${cron_entries[answer]}"

    # Delete the selected cron entry
    unset cron_entries["$answer"]

    # Send the edited cron entries back to crontab
    printf '%s\n' "${cron_entries[@]}" | crontab -
  else
    printf '\nAborted with choice %q\nNo job deleted\n' "$answer"
  fi
else
  printf 'There is no cron job for user: %s\n' "$USER"
fi
Léa Gris
  • 17,497
  • 4
  • 32
  • 41