shutdown 命令用于安全地关闭或重启Linux系统。它会向所有登录用户发送警告消息,在指定时间后执行关机操作,并允许管理员优雅地终止进程。
shutdown [选项] [时间] [警告消息]
| 参数 | 说明 |
|---|---|
-h |
关机后停止系统(halt) |
-r |
重启系统 |
-c |
取消已安排的关机计划 |
-k |
只发送警告消息,不真正关机 |
-t 秒数 |
指定发送SIGTERM信号前的延迟秒数 |
--no-wall |
关机前不发送警告消息 |
-P |
关机后切断电源(默认) |
-H |
关机后停止系统但不切断电源 |
| 时间格式 | 示例 | 说明 |
|---|---|---|
now 或 +0 |
shutdown now |
立即执行 |
+分钟数 |
shutdown +5 |
5分钟后执行 |
HH:MM |
shutdown 22:30 |
在指定时间执行(24小时制) |
yyyy-mm-dd HH:MM |
shutdown 2024-12-31 23:59 |
在指定日期时间执行 |
# 立即关机
sudo shutdown -h now
# 或使用
sudo shutdown now
# 10分钟后关机
sudo shutdown -h +10
# 今天22:30关机
sudo shutdown -h 22:30
# 指定日期时间关机
sudo shutdown -h 2024-12-31 23:59
# 立即重启
sudo shutdown -r now
# 5分钟后重启
sudo shutdown -r +5
# 15:00重启
sudo shutdown -r 15:00
# 取消所有已安排的关机计划
sudo shutdown -c
# 30分钟后关机,并发送自定义消息
sudo shutdown -h +30 "系统将在30分钟后进行维护关机,请保存您的工作!"
# 立即重启,发送消息
sudo shutdown -r now "系统即将重启进行更新"
测试关机警告消息,实际不执行关机:
# 发送警告但不会真正关机
sudo shutdown -k +5 "系统将在5分钟后关闭(测试消息)"
# 关机,在发送SIGTERM信号前等待10秒
sudo shutdown -h -t 10 now
# 关机前给进程30秒时间优雅退出
sudo shutdown -h -t 30 now
# 静默关机,不发送广播消息
sudo shutdown -h --no-wall now
计划在凌晨进行服务器维护:
# 凌晨2点重启服务器,提前1小时通知用户
sudo shutdown -r 02:00 "服务器将在凌晨2点进行维护重启,请提前保存工作!"
# 查看计划的任务
sudo atq
#!/bin/bash
# 执行数据处理任务
echo "开始数据处理..."
./data_processing.sh
# 任务完成后关机
echo "数据处理完成,系统将在1分钟后关机"
sudo shutdown -h +1 "数据处理任务已完成,系统将关机"
# SSH连接到远程服务器并设置定时关机
ssh user@server.example.com "sudo shutdown -h +60 '系统将在1小时后关机维护'"
# 检查远程服务器的关机计划
ssh user@server.example.com "sudo shutdown -c" # 如果需要取消
| 命令 | 功能 | 特点 | 建议使用场景 |
|---|---|---|---|
shutdown |
安全关机/重启 | 可定时、发送警告消息、优雅终止进程 | 生产服务器、多用户系统 |
poweroff |
立即关机断电 | 直接关机,不发送警告 | 单用户系统、紧急情况 |
halt |
停止系统运行 | 停止CPU,但可能不断电 | 系统维护、调试 |
reboot |
立即重启 | 直接重启,不发送警告 | 快速重启、单用户环境 |
init 0 |
切换到运行级别0(关机) | 传统SysV init关机方式 | 兼容旧系统 |
systemctl poweroff |
systemd关机 | 现代systemd系统关机方式 | systemd系统(CentOS 7+, Ubuntu 16.04+) |
# 关机
sudo shutdown -h now
# 或
sudo init 0
# 重启
sudo shutdown -r now
# 或
sudo init 6
# 关机(推荐)
sudo systemctl poweroff
# 重启
sudo systemctl reboot
# 定时关机(1小时后)
sudo systemctl poweroff --time=+1h
# 取消计划
sudo shutdown -c # shutdown命令仍然有效
shutdown命令通常需要root权限:
# 错误:普通用户执行
shutdown -h now
# 输出:shutdown: Need to be root
# 正确:使用sudo
sudo shutdown -h now
检查系统时间和时区设置:
# 查看系统时间
date
# 查看时区
timedatectl
# 设置时区(如设置为上海)
sudo timedatectl set-timezone Asia/Shanghai
某些服务可能阻止关机:
# 强制关机(不推荐,可能损坏数据)
sudo shutdown -h now --force
# 或使用更强制的方式
sudo poweroff -f
HH:MM格式避免混淆-k选项测试消息格式和接收情况在~/.bashrc中添加别名:
# 快速关机
alias off='sudo shutdown -h now'
# 快速重启
alias reboot='sudo shutdown -r now'
# 1小时后关机并发送消息
alias off1h='sudo shutdown -h +60 "系统将在1小时后关机"'
重新加载配置:source ~/.bashrc