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.

Submit an answer

This textbox defaults to using Markdown to format your answer.

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

Sign In or Sign Up to Answer

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.

Site Moderator
Site Moderator badge
January 7, 2020
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.


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


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

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel