Commands

Put a Timer on Your Running Commands With Timeout Command in Linux

With the timeout command you can set a time limit on running other commands and programs. If the program runs longer than the set limit, timeout kills it. Learn how to use it.

Abhishek Prakash
Abhishek Prakash

Table of Contents

With the timeout command you can set a time limit on running other commands and programs. If the program runs longer than the set limit, timeout kills it.

Sounds good, right? Let’s see how to use this command.

Using timeout command in Linux

Timeout Command

Here’s the syntax for the timeout command:

timeout [options] seconds command

As you can see, the time is always set in seconds here.

Let’s take an example with the sleep command. The sleep command basically ‘sleeps’ till the allotted time. Which means it just waits for that many seconds.

timeout 4 sleep 10

So if I use sleep 10, the shell waits for 10 seconds. But if I put a timeout of 4 seconds, the sleep command that was supposed to run for 10 seconds, ends in just 4 seconds.

By default, the timeout command sends SIGTERM to politely kill the running program. You may send some other signal using the -s option.

You can see all the kill signals in Linux with kill -l command. Let’s say you want to send the SIGKILL signal (kill -9) instead of the default, SIGTERM. You can use something like this:

timeout -s SIGKILL 3 sleep 30

You could also use KILL or 9 (the number for SIGKILL as listed in kill -l) instead of SIGKILL.

Hard killing a program is not a nice thing to do. But a program can ignore the SIGTERM.

A better way to handle is to send the kill signal only when your initial termination request is ignored by the running program.

So, let’s say you want to run a program not more than 5 seconds. But if the running program refuses to stop, you send the kill signal 3 seconds after sending the default SIGTERM. Here’s what you can use:

timeout -k 3 5 program

This means your program won’t run more than 8 seconds. You can use the time command to check how long did the program actually run.

Check Command and Script Completion Time with Time Command
The time command in Linux measures how long a particular command or script runs. Learn how to use this command.

Is there a practical use of timeout command?

It sounds like one of those obscure Linux commands that you might not use every day. It could, however, be useful in some special situations.

For example, if you started playing a terminal game to fresh your mood for a bit but you lost track of the time and kept on playing far more than the desired time.

The timeout command is helpful in such cases.

Stay tuned to learn more Linux commands. Do subscribe to the newsletter to receive regular tips and tricks.



Join the conversation.