创建脚本以检查交互式提示是否删除cron条目:
function cron_check()
{
crontab -l
result=$?
if [[ $result -eq 0 ]]; then
crontab -l > crontab.out
cat crontab.out | while read cron_entry
do
# ignore commented cron entries
[ "${cron_entry#\#}" = "$cron_entry" ] || continue # skip comment
read -u3 -p "Do you want to remove this cron entry: $cron_entry, Please enter [Y/N]" yn
case $yn in
[yY] | [yY][Ee][Ss] ) sed -i "/$cron_entry/d" crontab.out;;
[nN] | [n|N][O|o] ) break;;
* ) echo "Please answer Y or N.";;
esac
done 3<&0 < crontab.out
crontab crontab.out
fi
}
cron_check
然而,提示部分不起作用,在运行脚本时我得到:请回答Y或N.任何帮助如何解决这个问题? 谢谢!
答案 0 :(得分:3)
为了能够在你的情况下使用read,你需要使用特殊的文件描述符这样的东西:
while read crontab_entry; do ...
read -u3 -p 'question' yn
...
done 3<&0 < crontab.out
因为STDIN已经由crontab输出
提供答案 1 :(得分:0)
我使用了cat命令的特殊文件描述符,并对sed命令进行了一些修改才能正常工作。
function cron_check()
{
crontab -l
result=$?
if [[ $result -eq 0 ]]; then
crontab -l > crontab.out
exec 3< crontab.out
while read -u 3 cron_entry
do
# ignore commented cron entries
[ "${cron_entry#\#}" = "$cron_entry" ] || continue # skip comment
read -p "Do you want to remove this cron entry: $cron_entry, Please enter [Y/N]" yn
case $yn in
[yY] | [yY][Ee][Ss] ) cron_entry_esc=$(sed 's/[\*\.&/]/\\&/g' <<<"$cron_entry");crontab -l | sed "/$cron_entry_esc/d" | crontab -;;
[nN] | [n|N][O|o] ) continue;;
* ) echo "Please answer Y or N.";;
esac
done
fi
}
cron_check