I'm looking for a way to act differently in my bash
script depending on my external IP address. To be more specific if my external IP address is 111.111.111.111
then do some action, otherwise do something else.
This is my code:
extIP=$(curl ifconfig.me | grep 111.111.111.111)
if [ -? ${extIP} ]
then
runExecutable
else
echo "111.111.111.111 is not your IP."
fi
I don't know how to test extIP
.
Try this
echo 'Enter the IP Address you want to test'
read IP_ADDRESS
extIP=$(curl ifconfig.me | grep -o '[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*')
if [ "$IP_ADDRESS" == "$extIP" ]
then
bash runExecutable.sh
exit 0
fi
echo '${IP_ADDRESS} is not your IP'
exit 1 # if it's bad or just exit 0 otherwise
Just run the curl/grep command the check the exit status
curl ifconfig.me | grep -s 111.111.111.111
if [ "$?" == "0" ]
then
runExecutable
else
echo "111.111.111.111 is not your IP."
fi
You should test the exit code of your command pipeline directly with if
, like this:
addr="111.111.111.111"
if curl -s ifconfig.me | grep -qF "$addr"; then
runExecutable "$addr" ...
else
echo "$addr is not your IP."
fi
Also, you probably want to silence the curl
's progress output with -s
and grep
's matches with -q
, use a fixed string search in grep
with -F
, and store your IP address in a variable for easier later reuse.
Note the [
is actually a shell command that exits with 0
if condition that follows is true, or with 1
otherwise. if
than uses that exit code for branching.
See this bash pitfall for more details.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.