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:

  1. Using the timeout command: The timeout 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
  1. Using the bash built-in timeout command: If the timeout command is not available, you can use the bash built-in timeout 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
  1. 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
  1. Using the GNU time command : The time 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.

(www.beyondbeaute.com)

Leave a Comment