语法非常简单:timeout [选项] 时长 命令
timeout 5s ping baidu.com#5秒后自动停止,干净利落。

备注:原生ping不加参数,部分系统会永久执行,只能手动杀进程。
timeout 20s ssh root@server "df -h"timeout 20s ssh root@127.0.0.1 "df -h"

timeout 30m ./2.sh#限制脚本最长执行时间是30分钟

-k 参数更安全:到时间不退出,直接强制杀死。timeout -k 3s 10s ./ceshi.sh
10 秒优雅退出,不行就 3 秒强杀,防止僵尸进程。
生成环境80%的定时任务服务器负载异常,都是备份脚本超时堆积导致。直接在crontab内嵌套timeout,无需改动原有脚本:
#/etc/crontab#每天凌晨2点备份,最多运行2小时0 2 * * * root timeout 2h /opt/scripts/backup.sh
#!/bin/bash#业务服务健康检查,5秒内必须响应if timeout 5s curl -sf http://localhost:8080/health; thenecho "服务健康"exit 0elseif [ $? -eq 124 ]; thenecho "服务响应超时"elseecho "服务异常"fisystemctl restart myappexit 1fi

#!/bin/bash#批量执行ping命令for ip in 192.168.2.{1..10}; doecho "检查 $ip..."if ping -c1 -W3 "$ip" &>/dev/null;thenecho "$ip 通"elseecho "$ip 不通"fidone

#timeout只终止直接进程,不终止子进程,如果命令创建了子进程,可能还会残留timeout 5s ./create_child.sh#子进程可能还在运行#解决方法:使用进程组timeout 5s sh -c './2.sh & wait'
#timeout对后台任务&无效timeout 5s sleep 10 & #后台任务不会超时#正确做法timeout 5s sh -c 'sleep 10 & wait'

#管道中的每个命令都有独立的timeouttimeout 5s command1 | command2#command1有5秒限制,command2没有#正确做法timeout 5s sh -c 'command1 | command2'#常用写法1:只有sleep1受5秒限制,sleep2一直跑timeout 5s sleep 10 | sleep 20#常用写法2:整条管道整体5s超时,两个sleep一起被杀timeout 5s sh -c 'sleep 10 | sleep 20'

timeout虽小,却是linux 实战里高频好用的效率工具。不管是日常命令、定时任务、自动化脚本,加上它就能避免卡死、超时、资源浪费,运维必备。下次遇到命令跑不停,别再手动等待,直接用 timeout 搞定!如果你觉得文章对你的运维工作有帮助,记得点赞加关注。