There are a few ways to run a command with a time limit (timeout) on Linux. Here are a few options:
- Using the
timeout
command: Thetimeout
command is a coreutils utility that can be used to run a command with a specified time limit. The syntax is as follows:
timeout <duration> <command>
For example, to run the command ping google.com
for a maximum of 5 seconds, you can use the following command:
timeout 5 ping google.com
- Using the
bash
built-intimeout
command: If thetimeout
command is not available, you can use thebash
built-intimeout
command. The syntax is as follows:
bash -c 'command; sleep <duration>; kill -9 $$' & disown
For example, to run the command ping google.com
for a maximum of 5 seconds, you can use the following command:
bash -c 'ping google.com; sleep 5; kill -9 $$' & disown
- Using the
timeout
function : You can define a function to run the command with a time limit, you can use the following function:
timeout() {
time=$1
command="${@:2}"
( $command & pid=$!; sleep $time; kill -9 $pid ) 2>/dev/null &
disown
}
For example, to run the command ping google.com
for a maximum of 5 seconds, you can use the following command:
timeout 5 ping google.com
- Using the
GNU time
command : Thetime
command is a GNU tool that can be used to measure the execution time of a command. It can also be used to run a command with a time limit using the-k
option.
time -k <duration> <command>
For example, to run the command ping google.com
for a maximum of 5 seconds, you can use the following command:
time -k 5s ping google.com
Note that the above commands will kill the command if it runs longer than the specified time limit, so be careful when using them.