我正在嘗試為我的伺服器編寫一個 bash 腳本。這個腳本的作用是運行curl來獲取我的盒子的最新IP位址,如果它與檔案中儲存的舊IP位址不同,然後給我發電子郵件。
這就是我現在所擁有的:
#!/bin/bash
#if ip address changes do
x=$(curl -4 "icanhazip.com")
y=$(cat ./oldIP.txt )
if [ "$x"!="$y" ];
then
echo "Current IP Address is $x"
echo "Previous IP address is $y"
# y=$x
elif [ "$x"="$y"]
then
echo "The IP addresses are the same"
fi
#send email to me
我也嘗試過使用,if; then; else;
但是當 IP 位址相同時,我無法讓腳本做出不同的反應。
我相信問題源自於我的變數宣告$y
。
答案1
測試括號 [ ] 內的運算元之間必須留有空格。
#!/bin/bash
#if ip address changes do
x=$(curl -4 icanhazip.com )
y=$(cat ./oldIP.txt )
if [ "$x" != "$y" ]
then
echo "Current IP Address is $x"
echo "Previous IP address is $y"
# y=$x
else
echo "The IP addresses are the same"
fi
#send email to me