service="/sbin/service" # 检查cron服务状态 cron_status=$(service cron status) if grep -q "unrecognized" <<< "$cron_status" then echo "cron未安装" elif grep -q "is not running" <<< "$cron_status" then echo "正在启动 cron 服务" sudo service cron start elif grep -q "is running" <<< "$cron_status" then echo "cron已启动" else echo "未知状态" fi # 检查自启动状态 if [ `systemctl list-unit-files cron.service | grep -c -e "cron.service\senabled"` -ne '0' ] then echo "开启启动已设置" else echo "正在设置开机启动" sudo systemctl enable cron fi CURRENT_DIR=$(cd "$(dirname "$0")";pwd) find_file="${CURRENT_DIR}/cron.conf" find_str="mysql_backup_run" crontab -l > ${find_file} task="0 4 * * * bash ${CURRENT_DIR}/mysql_backup_run.sh" # 检查记录中是否有mysql_backup_run条目数据 if [ `grep -c "${find_str}" ${find_file}` -ne '0' ] then echo "已存在备份计划任务" echo "若需更新备份计划任务,请运行mysql_backup_stop.sh删除备份计划任务,再运行本脚本" else echo "正在添加备份计划任务" echo "$task" >> ${find_file} crontab ${find_file} fi echo "最终cron任务如下:" cat ${find_file} rm -f ${find_file} if [ `crontab -l | grep -c "$find_str"` -ne '0' ];then echo "启动成功!" else echo "启动失败!" fi