0

I am working on a distributed Linux system.In my bash script I want to grep the output of :

ssh $ipaddress ibstat

The above command will hang if the machine is down. How do I handle the hang and come out of a the bash script with a non-zero value?

3 Answers 3

1

Use the ConnectTimeOut option with a low value, which you may need to adjust for your particular environment:

$ ssh -o ConnectTimeout=2 $ipaddress
ssh: connect to host 192.168.123.123 port 22: Connection timed out
$ echo $?
255

You even get a return value which you can test - 255 means an error occurred processing the command.

3
  • Your ssh gives an error : ssh: connect to host 192.168.123.123 port 22: Connection timed out . Mine does not give an error, it just hangs.I have to press CTRL+C to come out of it.
    – kyabhft
    Jan 10, 2020 at 9:22
  • Do you get any other message, such as ssh: Ignoring unknown configuration option 'ConnectTimeout=2 ? The above was tested on Debian and Alpine running openssh client. Jan 10, 2020 at 10:04
  • No it does not. Mine is a SUSE .
    – kyabhft
    Jan 10, 2020 at 10:14
0

The timeout utility may be your choice for that:

timeout 5 ssh $ipaddress ibstat

will exit with non-zero result after 5 seconds, set it to a reasonable value sufficient for ibstat to complete

3
  • I will try this and update. Thanks!!
    – kyabhft
    Jan 10, 2020 at 10:39
  • There is a problem with timeout : If the ssh is proper and I give an extra second for it to run, it will come out only after the timeout and will always return a non- zero value which should not be the case. Also if we wait the failed case will unnecessarily wait for those seconds.
    – kyabhft
    Jan 13, 2020 at 13:28
  • There will be no extra waiting till the timeout expires if ssh remote command finishes normally before the timeout value. If remote command fails, it too will return immediately, not waiting till the end of timeout, and the exit code will be different from the exit code of timeout itself.
    – Tagwint
    Jan 13, 2020 at 14:25
0

You can try to check host availability first:

if ping -c 1 $ipaddress &> /dev/null
then
  ssh $ipaddress ibstat
else
  exit 1
fi
3
  • The ping works fine but the ssh hangs.
    – kyabhft
    Jan 10, 2020 at 7:13
  • You wrote: The above command will hang if the machine is down. So, just use ping command for checking host is alive. Try it: -o ServerAliveInterval=<secs>, for aborting connection
    – spybull
    Jan 10, 2020 at 7:30
  • I will try this and update. Thanks!!
    – kyabhft
    Jan 10, 2020 at 10:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.