user1944429
user1944429

Reputation:

Simple bash function to check if a ssh session succeeded or not

When I'm at home, I want to connect to my server using my local network because it's faster than connecting to it's external IP address. But I want a function that connects automatically to my internal IP's SSH session, with capability for parameters, and if it fails try the external IP (and, again use the parameters).

So far what I have is this, and it seems like it should work, and I'm having a heck of a time debugging it.

ssh_home() { if ssh [email protected] "$@" then echo; else echo "WARNING: NOT on home connection!"; ssh [email protected] -p 10000 "$@"; fi; }

The error message I'm currently getting is:

syntax error near unexpected token `else'

But I've looked up if else statements, and I'm pretty sure I'm doing it right.. Maybe my eyes are completely missing something though.

Upvotes: 1

Views: 135

Answers (1)

janos
janos

Reputation: 124656

You forgot a semicolon in front of the then:

ssh_home() { if ssh [email protected] "$@"; then echo; else echo "WARNING: NOT on home connection!"; ssh [email protected] -p 10000 "$@"; fi; }

In any case, why echo there nothing? why not reverse the condition:

ssh_home() { if ! ssh [email protected] "$@"; then echo "WARNING: NOT on home connection!"; ssh [email protected] -p 10000 "$@"; fi; }

And why not write the function on multiple lines so it's easier to read:

ssh_home() {
    if ! ssh [email protected] "$@"; then
        echo "WARNING: NOT on home connection!"
        ssh [email protected] -p 10000 "$@"
    fi
}

Upvotes: 2

Related Questions