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?

Philip Kirkbride
  • 9,816
  • 25
  • 95
  • 167

3 Answers3

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.

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
2

Use timeout.

timeout 2 sleep 1
echo $?
0

timeout 1 sleep 2
echo $?
124
Matt Clark
  • 365
  • 1
  • 2
  • 16
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.

Garth Kidd
  • 121
  • 3