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.
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!
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.
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:
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.
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:
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.