如果下次检查 IP 地址没有更改,如何停止执行 bash 脚本?

如果下次检查 IP 地址没有更改,如何停止执行 bash 脚本?

我已尽力使用标题,但如果我为您提供一个简单的示例来说明 bash 脚本中需要完成的操作,那就更好了。

curl ident.me
#this one checks my current public IP address

curl [a post request]
#sending a curl post request

curl ident.me
#again, it checks my current public IP address

curl [a different post request]
#it will send the curl post request ONLY if the IP address we got with the previous curl request is DIFFERENT than the one we got when we previously used the same command to check for the current IP address. If it's not different, it should stop/pause the script.

有任何想法吗 ?由于从技术上精确地表达这个问题的困难,谷歌没有提供任何帮助。

答案1

我会将每个curl 的结果存储在一个变量中,然后在if 语句中比较每个curl 的结果是否相互匹配。

a=$(curl ident.me)
curl [a post request]
b=$(curl ident.me)

if [ "$a" != "$b" ]
then
  echo "do not match" && ...
else 
  exit
fi

答案2

一个函数会让事情变得更容易:

die() { printf>&2 '%s\n' "$@"; exit 1; }

ip= prev_ip=
retrieve_public_ip() {
  ip=$(curl --no-progress-meter https://ident.me) && [ -n "$ip" ] ||
    die "Can't determine my public IP address"

  [ "$ip" != "$prev_ip" ] ||
    die "My public IP address has not changed. Aborting"

  prev_ip=$ip
}

retrieve_public_ip
curl [a post request]

retrieve_public_ip
curl [a different post request]

# and so on.

相关内容