How To Use Timeout Command In Linux

Timeout command is handy at times when we want to terminate a task after fixed interval of time.

Timeout should be installed on every Linux by default. To find out the usage of timeout do following...

sudo timeout --help | less

You should see following.

sudo timeout [OPTIONS] DURATION COMMAND [ARG]

The basic format is timeout and then the duration for which we want to run a particular command and then the command itself.

Timeout Usage with examples

ping an ip using timeout

sudo timeout 5 ping 149.56.26.138

Above command will run for 5 sec and then terminate the ping command automatically.

If we do echo $?, you should see following output...

sudo echo $?
124

This is the value timeout uses to indicate the program was terminated using SIGTERM.

If we want timeout to preserve the value with which command exited, use the --preserve-status switch as shown below.

sudo timeout --preserve-status 5 ping 149.56.26.138

If we do echo now, we would see different status...

sudo echo $?
143

tcpdump using timeout

sudo timeout 300 tcpdump -n -w data.tdump

top command using timeout

Similarly we can run top command using timeout.

sudo timeout --preserve-status 5 top

Since we used preserver-status switch, when we use echo $?, switch we should see exit status from the command top not 124 from timeout

sudo echo $?
0

timeout --foreground example

timeout can time out any command as long as the timeout is initiated from the bash shell. What if you use timeout inside timeout. example...

timeout 1 timeout 2 bash

You would think that inner timeout will kill the new bash shell in 2 secs and then outer timeout will kill the inner timeout after 1 sec. But if you try above command, you would see the command would get stuck and not terminated. The reason is that inner timeout has not been run from the bash but as tty input.

To make it work we will have to use --foreground switch as shown below.

timeout 1 timeout --foreground 2 bash