Bash: ssh 输入到 while 循环

Bash: ssh input to while loop

我正在尝试查询远程服务器上日志文件的内容,但是,我似乎无法让它工作。

#!/bin/bash
while read line; do
        echo "Do stuff to the file, line by line"
done < ( ssh -n user@server "cat /path/to/file" )

第一个括号处出现语法错误。如果我删除括号,我会在“-n”标志处收到语法错误。

从 shell 开始一切正常,所以我假设这里有一些我没有正确理解的行为。

谢谢!

您需要另一个 < 用于进程替换。

#!/bin/bash
while read line; do
        echo "Do stuff to the file, line by line"
done < <( ssh -n user@server "cat /path/to/file" )

第一个<指定输入重定向。 <(...) 构造是进程替换,类似于命令替换,但将封闭命令的输出视为文件,而不是字符串。