現象と原因
while read 内でsshを実施するとループしない whire read 内でSSH を実行すると,標準入力がそちらに振り向けられるため,read で読んだ1行のみならず,ファイル全体が SSH に渡されてしまう. ssh先で標準入力を行なう処理をしたい場合にはおとなしくfor を使いましょう.
cat ${hostfile} | while read host do ssh ${host} "<任意のコマンド>" done
解決
ssh に -n オプションを付けることで解決できます.
cat ${hostfile} | while read host do ssh -n ${host} "<任意のコマンド>" done
検証
-n がない場合
main.sh
#!/bin/bash hostfile=./host.txt cat ${hostfile} | while read host do ssh ${host} "hostname;pwd" done
実行
# bash -v main.sh #!/bin/bash hostfile=./host.txt cat ${hostfile} | while read host do ssh ${host} "hostname;pwd" done 172.0.0.1 /root echo "END" END
-n がある場合
main.sh
#!/bin/bash hostfile=./host.txt cat ${hostfile} | while read host do ssh -n ${host} "hostname;pwd" done
実行
# bash -v main.sh #!/bin/bash hostfile=./host.txt cat ${hostfile} | while read host do ssh -n ${host} "hostname;pwd" done 172.0.0.1 /root 172.0.0.2 /root