帮我写个shell脚本定时关机
以下是一个简单的定时关机脚本:
#!/bin/bash
# 设置关机时间,格式为HH:MM
shutdown_time="23:00"
# 获取当前时间,格式为HH:MM
current_time=$(date +%H:%M)
# 判断当前时间是否大于关机时间
if [[ $current_time > $shutdown_time ]]; then
# 如果是,则立即关机
sudo shutdown -h now
else
# 如果不是,则计算距离关机时间还有多久,并设置定时任务
seconds=$(( $(date -d "$shutdown_time" +%s) - $(date +%s) ))
sudo shutdown -h +$((seconds/60))
fi
使用方法:
- 复制上面的代码到一个新的文本文件中,例如
shutdown.sh。 - 修改
shutdown_time变量的值为你想要的关机时间,例如22:30。 - 打开终端,进入脚本所在的目录,运行
chmod +x shutdown.sh命令,将脚本设置为可执行。 - 运行
./shutdown.sh命令,测试脚本是否可以正常工作。 - 如果测试通过,可以将脚本添加到定时任务中,例如每天晚上10点半执行一次关机操作。具体方法可以参考Linux系统的定时任务相关文档。
原文地址: http://www.cveoy.top/t/topic/bs6u 著作权归作者所有。请勿转载和采集!