Bash

使用 for 讀取文件,while - 行為

  • August 12, 2016

考慮以下場景

2 個虛擬機 - 192.168.229.131、192.168.229.132

/etc/hosts兩個虛擬機的文件中都有 192.168.229.151 和 192.168.229.152 的 IP

假設像我上面所說的那樣大約有 50 個虛擬機。但截至目前,我只考慮上述2個。

我將 2 個 vm 的 ips 保存在一個名為 server 的文件中

#cat server
192.168.229.131
192.168.229.132

下面是腳本

#!/bin/bash
cat server | while read line
do
/usr/bin/sshpass -e ssh -t -q -o StrictHostKeyChecking=no root@$line << EOF
echo successfully logged in $line
MYIP=$(ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')
for i in 151 152
do
echo 192.168.229.\$i >> errips
done
for data in `cat errips`
do
echo data currently has $data
grep $data /etc/hosts
if [ $? -eq 0 ]
then
sed -i "s/$data/$MYIP/g" /etc/hosts
echo "completed"
unset MYIP
rm -rf errips
exit 0
fi
done
EOF
done

下面是輸出

root@master:~# ./script
cat: errips: No such file or directory
successfully logged in 192.168.229.131
cat: errips: No such file or directory
successfully logged in 192.168.229.132

為什麼登錄伺服器後的for循環在登錄前執行?

我嘗試使用以下內容而不是“for”

cat errips |while read line
echo line currently has $line

在這種情況下,我發現該行仍然從 localhost 中的伺服器文件中獲取 IP,而它應該從我遠端登錄的伺服器的 errips 文件中讀取它。

輸出是

line currently has 192.168.229.131
line currently has 192.168.229.132

而我希望它應該讀取文件“errips”中的值,輸出應該如下所示

line currently has 192.168.229.151
line currently has 192.168.229.151

現在,我嘗試了以下命令

cat errips |while read data
echo data currently has $data

在這種情況下,值數據的輸出為空

data currently has 
data currently has

我將如何逐行讀取遠端伺服器中的文件“errips”,並在 /etc/hosts 中對行進行 grep,然後執行 if 循環,它將用正確的 ip 替換錯誤的 ip?

您需要單引號您的此處文件限製字元串,否則將啟用參數替換。這應該有效:

#!/bin/bash
cat server | while read line
do
 /usr/bin/sshpass -e ssh -t -q -o StrictHostKeyChecking=no root@$line <<'EOF'
 echo successfully logged in $line
 MYIP=$(ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')
 for i in 151 152
 do
   echo 192.168.229.$i >> errips
 done
 for data in `cat errips`
 do
   echo data currently has $data
   grep $data /etc/hosts
   if [ $? -eq 0 ]
   then
     sed -i "s/$data/$MYIP/g" /etc/hosts
     echo "completed"
     unset MYIP
     rm -rf errips
     exit 0
   fi
 done
EOF
done

請注意 EOF 周圍的單引號。要進一步說明,請嘗試以下操作:

/usr/bin/sshpass -e ssh -t -q -o StrictHostKeyChecking=no root@<your_ip> 'k=1; echo $k'
/usr/bin/sshpass -e ssh -t -q -o StrictHostKeyChecking=no root@<your_ip> "k=1; echo $k"
/usr/bin/sshpass -e ssh -t -q -o StrictHostKeyChecking=no root@<your_ip> "k=1; echo \$k"

引用自:https://unix.stackexchange.com/questions/162833