16

I'm trying to run something like:

sudo dhclient $wifi || otherFunction

Problem is when dhclient fails it just hangs instead of throwing an error.

How can I re-write the above so dhclient is killed and otherFunction gets called if dhclient doesn't finish in 60 seconds?

3 Answers 3

18

Your tag gives it all away:

sudo timeout 60 dhclient $wifi || otherFunction

An example:

sudo timeout 3 sleep 5 || echo finished early

This uses the timeout utility provided by the GNU coreutils package on Linux.

3
  • 2
    doesn't work on MacOS unfortunately Apr 20, 2018 at 22:13
  • timeout for MacOS: stackoverflow.com/a/21118126/451480
    – Blaise
    Feb 10, 2019 at 21:29
  • If you want to check specifically for timeout killing the command (as opposed to the command failing for other reasons), check for exit status 124.
    – muru
    Jun 26, 2019 at 8:48
2

Use timeout.

timeout 2 sleep 1
echo $?
0

timeout 1 sleep 2
echo $?
124
1
  • 1
    doesn't work on MacOS unfortunately Apr 20, 2018 at 22:13
2

Use the timeout packed as gtimeout with the coreutils port in brew:

brew install coreutils
gtimeout --help

That'll work with /usr/local/bin in your PATH. If you want to use timeout as originally named, add /usr/local/opt/coreutils/libexec/gnubin to your PATH.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .