How to Set Execution Time Limits Using the timeout Command in Linux

When you are writing automated bash scripts for a Linux server, you often rely on external network commands like ping, curl, or wget. If the remote server you are trying to contact is offline, these commands can hang indefinitely, completely freezing your script and stalling your entire deployment pipeline. To prevent commands from hanging forever, you must wrap them in the Linux timeout command.

How the timeout Command Works

The timeout utility acts as a strict timekeeper for any command you pass to it. You specify a time limit, and timeout launches the target command in the background. If the command finishes successfully before the clock runs out, everything proceeds normally. If the clock hits zero and the command is still running, timeout acts like a sniper; it instantly sends a termination signal (SIGTERM) to the process, forcefully killing it and returning control of the terminal back to you.

How to Set a Basic Time Limit

To use it, type timeout, followed by the duration, followed by the command you want to execute.

For example, the ping command on Linux runs infinitely by default. To force a ping command to abort after exactly 5 seconds, run:

timeout 5 ping google.com

The terminal will ping Google normally, but the exact millisecond the 5-second timer expires, the ping process will be violently killed and you will be returned to your command prompt.

By default, the number represents seconds. However, you can append suffixes to configure much longer limits. Use m for minutes, h for hours, and d for days.

timeout 2h wget http://massive-file.iso

This command allows the file download to run for exactly 2 hours before aborting it.

Forcing a Hard Kill (SIGKILL)

When the timer expires, timeout politely asks the program to stop by sending a standard SIGTERM (Signal 15). Well-behaved programs receive this signal, clean up their temporary files, and shut down. However, frozen, buggy, or zombie processes often ignore SIGTERM entirely.

If a program ignores the termination signal, it will keep running even after the timeout expires. To prevent this, you can use the -k (kill-after) flag to deploy a brutal, un-ignorable SIGKILL (Signal 9).

timeout -k 10s 30s buggy_script.sh

This complex command tells Linux: “Allow buggy_script.sh to run for 30 seconds. If it doesn’t finish, send a polite SIGTERM. Wait 10 more seconds. If the script is still running, send a ruthless SIGKILL to instantly destroy the process.” This guarantees that your automated scripts will never hang indefinitely.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.