This question already has answers here:
Use sed to edit crontab
(2个答案)
六天前关门。
我正在编写一个脚本,希望能够删除用户可以使用Crontab命令创建的特定作业/任务。
我知道,要简单地删除所有作业/任务,只需使用:
crontab -r;

但是,如果有多个作业/任务,如何列出它们,然后删除选定的作业/任务?

最佳答案

显示可用索引的可用作业,
读取用户选择,
按作业索引删除作业

#!/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

07-24 09:44
查看更多