Operations 4 min read

Mastering Shell Script Timeouts with the Linux timeout Command

This article explains how to use the Linux timeout command to reliably enforce execution limits on shell scripts, demonstrates its advantages over simple watchdog loops, shows practical examples with ping and MQ scripts, discusses return codes, and highlights common pitfalls such as background processes and function usage.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Shell Script Timeouts with the Linux timeout Command

In shell scripting, scripts can sometimes hang, leading developers to use crude watchdog loops that may kill the wrong process when new background jobs start.

To avoid indiscriminate termination, the built‑in #man timeout command (available on CentOS 6) should be used.

For example, to ping www.baidu.com but stop after 5 seconds of no response, run: #timeout 5s ping www.baidu.com The command exits after five seconds, as shown in the following output:

Building on this, the author improves a previously written MQ watchdog script by adding timeout monitoring and email alerts for failures. The original script took about 13 seconds to run; a timeout of 20 seconds is set, and the execution result is displayed:

When the script finishes normally it returns code 0; if it is terminated by the timeout, it returns code 124 (while a manual Ctrl+C yields 130). This behavior is illustrated below:

The final script (shown as an image) can be placed in crontab for scheduled execution.

Additional notes:

Using #timeout 3s ping www.baidu.com is not ideal because the Unix ping command repeats indefinitely; a better test is #timeout 3s sleep 1 versus #timeout 3s sleep 5 to observe timeout behavior.

The timeout command does not work when its argument is a shell function.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ShellcronBashTimeoutscript
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.