删除 Crontab 中现有的 job/task
Deleting an existing job/task in Crontab
我正在编写一个脚本,我希望能够删除用户可以使用 Crontab 命令创建的特定 job/task。
我知道要能够简单地删除所有 jobs/tasks,您只需使用:
crontab -r;
但是如果有多个 jobs/tasks 你如何列出它们然后删除选定的?
使用crontab -e
,它应该在系统编辑器中打开所有cron 任务,然后您删除特定的条目并保存并退出。干杯
编辑:添加从脚本中移除
你可以这样做 -
crontab -l | grep -v '<SPECIFICS OF YOUR SCRIPT HERE>' | crontab -
来自您的脚本。试一试,如果有效请告诉我
显示带索引的可用职位,
阅读用户选择,
按索引删除作业
#!/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
我正在编写一个脚本,我希望能够删除用户可以使用 Crontab 命令创建的特定 job/task。
我知道要能够简单地删除所有 jobs/tasks,您只需使用:
crontab -r;
但是如果有多个 jobs/tasks 你如何列出它们然后删除选定的?
使用crontab -e
,它应该在系统编辑器中打开所有cron 任务,然后您删除特定的条目并保存并退出。干杯
编辑:添加从脚本中移除
你可以这样做 -
crontab -l | grep -v '<SPECIFICS OF YOUR SCRIPT HERE>' | crontab -
来自您的脚本。试一试,如果有效请告诉我
显示带索引的可用职位, 阅读用户选择, 按索引删除作业
#!/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