Linux run a command with a time limit (timeout)

‮//:sptth‬www.lautturi.com
Linux run a command with a time limit (timeout)

You can use the timeout command to run a command with a time limit in Linux. The timeout command is part of the GNU coreutils package, which is available on most Linux distributions.

Here's an example of how to use the timeout command to run a command with a time limit of 10 seconds:

timeout 10 command-to-run

If the command-to-run takes longer than 10 seconds to complete, the timeout command will kill it and exit with a non-zero exit code.

You can also specify a different time unit other than seconds by using the -t option. For example, to run a command with a time limit of 1 minute:

timeout -t 60 command-to-run

You can use the -k option to specify a delay before the command is killed. For example, to run a command with a time limit of 10 seconds and a 5-second kill delay:

timeout -k 5 10 command-to-run

For more information about the timeout command and its options, you can consult the man page by running man timeout in the terminal.

Alternatively, you can use the bash builtin read command to implement a timeout when running a command. For example:

{ command-to-run & pid=$!; } && { sleep 10; kill -0 $pid 2> /dev/null && kill -9 $pid; }

This will run command-to-run in the background and store its process ID in the pid variable. The sleep 10 command will run for 10 seconds, and then the kill -0 $pid command will check if the process is still running. If it is, the kill -9 $pid command will be run to force the process to terminate.

You can adjust the time limit by changing the value passed to the sleep command.

Created Time:2017-10-30 10:17:42  Author:lautturi