Linux run a command with a time limit (timeout)
There are a few ways to run a command with a time limit (timeout) on Linux. Here are a few options:
- Using the
timeoutcommand: Thetimeoutcommand 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
bashbuilt-intimeoutcommand: If thetimeoutcommand is not available, you can use thebashbuilt-intimeoutcommand. The syntax is as follows:
bash -c 'command; sleep <duration>; kill -9 $$' & disownFor 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
timeoutfunction : You can define a function to run the command with a time limit, you can use the following function:
timeout() {
n time=$1
n command="${@:2}" ( $command & pid=$!; sleep $time; kill -9 $pid ) 2>/dev/null &
n disown
n}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 timecommand : Thetimecommand 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-koption.
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.comNote that the above commands will kill the command if it runs longer than the specified time limit, so be careful when using them.
n (www.beyondbeaute.com)