温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Shell脚本如何定时执行

发布时间:2026-07-02 20:55:49 来源:亿速云 阅读:140 作者:小樊 栏目:系统运维

在 Linux 中,Shell 脚本定时执行最常用的方式是 crontab。下面从基础到进阶给你一个完整说明。


一、使用 crontab 定时执行(最常用)

1️⃣ 编辑定时任务

crontab -e

如果是第一次使用,会让你选择编辑器(推荐 nanovim)。


2️⃣ crontab 时间格式说明

* * * * * command
│ │ │ │ │
│ │ │ │ └── 星期几 (0-7, 0和7都是星期天)
│ │ │ └──── 月份 (1-12)
│ │ └────── 日期 (1-31)
│ └──────── 小时 (0-23)
└────────── 分钟 (0-59)

3️⃣ 常见示例

✅ 每分钟执行

* * * * * /home/user/test.sh

✅ 每小时执行一次

0 * * * * /home/user/test.sh

✅ 每天凌晨 2 点执行

0 2 * * * /home/user/test.sh

✅ 每周一凌晨 3 点

0 3 * * 1 /home/user/test.sh

✅ 每 5 分钟执行

*/5 * * * * /home/user/test.sh

4️⃣ 脚本必须有执行权限

chmod +x /home/user/test.sh

5️⃣ 重定向输出(强烈建议)

0 2 * * * /home/user/test.sh >> /home/user/log.txt 2>&1
  • >>:追加日志
  • 2>&1:错误输出也写入日志

二、查看 / 删除 crontab

查看当前定时任务

crontab -l

删除所有定时任务

crontab -r

三、系统级定时任务(不推荐新手)

/etc/crontab

格式略有不同(需要指定用户):

0 3 * * * root /home/user/test.sh

四、使用 systemd timer(现代 Linux)

适合需要秒级精度或复杂依赖的场景。

示例(简要)

# /etc/systemd/system/mytask.timer
[Unit]
Description=Run my script every hour

[Timer]
OnCalendar=hourly

[Install]
WantedBy=timers.target
# /etc/systemd/system/mytask.service
[Unit]
Description=My Script

[Service]
ExecStart=/home/user/test.sh

启动:

systemctl daemon-reload
systemctl enable --now mytask.timer

五、常见问题排查

❌ 脚本手动能跑,cron 不能跑

原因通常是:

  • 没有执行权限
  • 使用了相对路径
  • 环境变量不同

✅ 解决:

#!/bin/bash
cd /home/user
./test.sh

或在 crontab 中指定 PATH:

PATH=/usr/bin:/bin

六、总结推荐

场景 推荐方式
普通定时任务 crontab
系统服务级 systemd timer
一次性任务 at

如果你愿意,可以把你的 脚本内容 + 想执行的时间 发给我,我可以直接帮你写好 crontab 配置 ✅

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI