shell腳本執行衝突事件-ssh&while

今天發現一個問題:

先看下腳本內容:
root@pts/0 # cat !$
cat /tmp/test_nginx
ls *.txt | tr ' ' '\n' | while read line
do 
echo $line
if [ 'yes' == 'yes' ]
then
ssh  192.168.109.10 "echo 'yes'"
else
ssh 192.168.109.10 "echo 'no'"
fi
done

上面腳本很簡單,讀取當前目錄的全部以txt結尾的文件(實際上我只是取得循環次數),但咱們
運行腳本會發現腳本只循環一次就退出了。效果以下:

root@pts/0 # bash -x /tmp/test_nginx       
+ tr ' ' '\n'
+ ls 1.txt 2.txt ip.txt png.txt       
+ read line
+ echo 1.txt
1.txt
+ '[' yes == yes ']'
+ ssh 192.168.9.10 'echo '\''yes'\'''
yes
+ read line


此時恭喜你,你如願接觸到ssh 和while 衝突事件了!

辦法始終比較問題多。
解決辦法很簡單:

方法一:

  ssh  192.168.109.10 "echo 'yes'"  
  改成  ssh  192.168.109.10 "echo 'yes'"  < /dev/null
  
方法二:
  ssh  192.168.109.10 "echo 'yes'"  
  改成  ssh  -n 192.168.109.10 "echo 'yes'" 
  
  
產生的緣由:
ssh 命令將while未執行的循環給讀取了,下面內容能夠幫助你理解。

root@pts/0 # bash -x /tmp/test_nginx 
+ ls 1.txt 2.txt ip.txt png.txt
+ tr ' ' '\n'
+ read line
+ echo 1.txt
1.txt
+ '[' yes == yes ']'
+ ssh 192.168.9.10 cat     //咱們將命令改爲cat,就會發現了。
2.txt
ip.txt
png.txt
+ read line
相關文章
相關標籤/搜索