Is there an elegant way to test an IP address in a BASH script? I could do ifconfig and narrow down the IP using sed/awk, but I think there is a simpler solution.
My application is basically using SSH/SCP scripts when I'm in my intranet and while I'm not. So, I want this type of flow
if IP=192.168.1.1
then do this
else
then do that
Something fairly simple that you can modify to suit your needs:
EDIT: forgot the fgrep :)
If its a matter of differentiating if you are connected within your Intranet or not,
you could check with a quick short ping or arp attempt to a known internal server IP.
If the IP fails to respond, you are likely to be outside the Intranet.
There could be slight glitches (like the server being temporarily down).
These can be allowed (you mistakenly switch to the Internet mode),
Or, tested further with multiple checks (over different internal resources).
This is more a comment on the mikeB answer, but comments don't allow code so I'll post it as an answer:
You can use something like grep to find what you're looking for, such as
This can actually be simplified getting rid of the test ( [ is an alias for test) on the exit status, because if already checks exit status directly, which is how test communicates with if already:
And you can further simplify this by using the regex searches built into most bourne shells by using a case statement:
one (IMO, more complicated, and more prone to failure) method is to configure your dhcp client to save the assigned IP address to a convenient file somewhere.
e.g. with dhclient, you can just drop a script in /etc/dhcp3/dhclient-enter-hooks.d/ to save the current IP to a file, say /var/run/current-IP.txt
then your other scripts can just cat that file to get the current IP.
the problem with doing something like this is that it only tells you what your IP address was when it was last assigned by dhcp. It doesn't actually tell you what your IP address is now. they may be the same, or they may not.
ip addr show <DEVICE> | grep inet | grep -v inet6 | awk '{print $2}'
This should output your IP, hopefully. There's probably a more elegant way to do it, but this gets the job done regardless of elegance.