SSH to Two Addresses and Use the One That Connects First

pingshell-scriptsshzsh

I have a home computer (let’s call it franklin because that’s what I call it) that I often ssh into from my work laptop. When I’m at home, I ssh to franklin.local, and when I’m at work or anywhere else, I ssh to remote.address.of.franklin.

I want to have a function in my profile that always connects in the correct way for the situation. My network conditions often change (wired vs. wireless, different SSIDs, etc), so I’d prefer not to do it by detecting the state of the network, but rather:

  1. If franklin is available locally, connect locally,
  2. else, connect remotely

Here’s what I use now:

function franklin () {
    ping -c 5 "franklin.local" > /dev/null
    if [[ $? != 0 ]]
        then
        echo "franklin not available on local, so trying remote connection"
        ssh -p 22 remote.address.of.franklin
    else
        echo "franklin available on local network, so trying local connection"
        ssh username@franklin.local
    fi
}

The problem is, the ping takes time. My question is: can I execute both ssh commands simultaneously, and then automatically use whichever one connects first?

Best Answer

What about trying a simple OR from your shell?

ssh username@franklin.local || ssh -p 22 remote.address.of.franklin

I am not really familiar with ZSH, but I guess the evaluation logic would still be lazy, meaning that the second part is only evaluated if the first part fails. Of course the first command may stall for some time trying to figure out if franklin.local is available.

You could assign that command to an alias to shorten it up (like you did with the function).

Related Question