【问题标题】:Loop only iterates once with `ssh` in the body [duplicate]循环仅在正文中使用`ssh`迭代一次[重复]
【发布时间】:2014-07-19 06:04:15
【问题描述】:

我经常看到与...基本相同的问题


当我在循环体中调用 ssh 时,我的 while 循环仅迭代一次。
while read -r line; do
    ssh somehost "command $line"
done < argument_list.txt

【问题讨论】:

    标签: bash ssh


    【解决方案1】:

    ssh 也从标准输入中读取,因此第一次调用ssh 会在下一次调用read 之前消耗剩余的argument_list.txt。要解决此问题,请使用以下任一方法将 ssh 的标准输入从 /dev/null 重定向

    ssh somehost "command $line" < /dev/stdin
    

    ssh -n somehost "command $line"
    

    如果ssh 真的确实需要从标准输入读取,您不希望它从argument_list.txt 读取更多数据。在这种情况下,您需要为 while 循环使用不同的文件描述符。

    while read -r line <&3; do
        ssh somehost "command $line"
    done 3< argument_list.txt
    

    bash 和其他一些 shell 还允许 read 采用 -u 选项来指定文件描述符,有些人可能会觉得它更具可读性。

    while read -r -u 3 line; do
        ssh somehost "command $line"
    done 3< argument_list.txt
    

    【讨论】:

      猜你喜欢
      • 2011-11-16
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多