循环只在主体中使用 `ssh` 迭代一次 [英] Loop only iterates once with `ssh` in the body
问题描述
我经常看到与...基本相同的问题
I often see questions which are essentially the same as...
当我在循环体中调用
ssh
时,我的 while
循环只迭代一次.
My
while
loop only iterates once when I call ssh
in the body of the loop.
while read -r line; do
ssh somehost "command $line"
done < argument_list.txt
推荐答案
ssh
也从标准输入读取,所以第一次调用 ssh
消耗了剩余的 >argument_list.txt
在下一次调用 read
之前.要解决此问题,请使用
ssh
also reads from standard input, so the first call to ssh
consumes the rest of argument_list.txt
before the next call to read
. To fix, either redirect ssh
's standard input from /dev/null
using either
ssh somehost "command $line" < /dev/stdin
或
ssh -n somehost "command $line"
如果 ssh
确实确实需要从标准输入中读取,您不希望它从 argument_list.txt
.在这种情况下,您需要为 while 循环使用不同的文件描述符.
In the event that ssh
really does need to read from standard input, you don't want it reading more data from argument_list.txt
. In this case, you need to use a different file descriptor for the while loop.
while read -r line <&3; do
ssh somehost "command $line"
done 3< argument_list.txt
bash
和其他一些 shell 也允许 read
使用 -u
选项来指定文件描述符,有些人可能会发现它更具可读性.
bash
and some other shells also allow read
to take a -u
option to specify the file descriptor, which some might find more readable.
while read -r -u 3 line; do
ssh somehost "command $line"
done 3< argument_list.txt
这篇关于循环只在主体中使用 `ssh` 迭代一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!