Question

How to run a command with time limit in Linux

I recently was asked if there is an option to execute a command but also to specify a time limit (timeout) so the command can be executed for a certain amount of time.

Subscribe
Share

Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Accepted Answer

This is possible with the build-in command timeout. Linux has a command-line utility called a timeout, which enables you to execute a command with a time limit.

The syntax is as follows.

timeout [OPTION] DURATION COMMAND [ARG]...

An example is using a timeout for the with the ping command:

timeout 5  X.X.X.X

You can also use other options like minutes, hours and so on. It is also recommended to use the --kill-after option as sometimes the commands may continue to run even after timeout sends the initial signal.

timeout --kill-after=5 2s ping X.X.X.X

Other options:

The –preserve-status option allows timeout to exit with the same status as COMMAND, even when the command times out. timeout --preserve-status 10s ping X.X.X.X

The –foreground option when not running timeout directly from a shell prompt, allow COMMAND to read from the TTY and get TTY signals; in this mode, children of COMMAND will not be timed out:

For example you can ssh to a remote server and execute the top/htop command and then when the timeout is reached you will get back to the foreground:

timeout --foreground 30s ssh -t user@server htop

or

timeout --foreground 30s ssh -t user@server top

The timeout command is a simple way to let a command run for a given amount of time.

Hope this briefly explains the usage and the advantage of the timeout command.

Regards, Alex