问题
I am working on a BASH shell script where I need to be able to check and see if the IP address returned from:
dig $HOSTNAME +short
is within a particular subnet or not. For example, if part of 192.168.10.x or 10.130.10.x then do z else do y.
I am not sure how to manipulate or check the IP address after I have it stored in a variable so that I can build out the logical test described above.
回答1:
If your subnets are full class C then you can just do a substring check:
if [ ${IP#192.168.10.*} == ${IP} -a ${IP#10.130.10.*} == ${IP} ]
then
echo "not in either subnet"
else
echo "in one of the subnets"
fi
Edit: Note, this of course doesn't validate that the IPs are valid, but it alleviates the need for external tools.
回答2:
I ended up using the following code to make it work:
if [[ "$IP" == *10.130.10.* || "$IP" == *192.168.10.* ]]; then
mount code goes here
fi
Thanks for everyone's help and explaining things to me to allow me to further learn about scripting. It is really appreciated!
来源:https://stackoverflow.com/questions/7970251/bash-ip-address-check