Reputation: 12433
I am making bash script like this
if [ "if I am in local "]; then
ssh [email protected]
else
ssh [email protected]
fi
How could I get if I am in local or not?
Upvotes: 1
Views: 41
Reputation: 18381
This works with assumption then IP addresses starting with 10,127,197,172 are reserved IP for private network.
myIp=$(hostname -I) # or i based on your version.
echo $myIp |grep -q -P '(^127\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)'
if [ "$?" -eq 0 ];then
echo "Private Network"
else
echo "Over Internet"
fi
Inspiration from Here .
Upvotes: 1
Reputation: 113864
One possibility is to test whether 192.168.11
is ping-able:
if ping -qc1 192.168.11 >/dev/null; then
ssh [email protected]
else
ssh [email protected]
fi
If ping
receives a response from 192.168.11
, then it exits with return code 0 (success) and the then
clause is executed. If no responses are returned, the else
clause is executed.
The option -c1
tells ping
to only send one packet. If your local network is unreliable (unlikely), you may need to send more than one packet.
The -q
option tells ping
to be a bit more quiet but that doesn't really matter because we dump its output into /dev/null
.
Note that IP addresses are typically written with 4 values, not 3: a number may be missing from 192.168.11
.
From man ping
:
If ping does not receive any reply packets at all it will exit with code 1. If a packet count and deadline are both specified, and fewer than count packets are received by the time the deadline has arrived, it will also exit with code 1. On other error it exits with code 2. Otherwise it exits with code 0. This makes it possible to use the exit code to see if a host is alive or not.
Upvotes: 1