通过 ssh 删除远程文件会停止命令所在的 while 循环吗?

Removing a remote file through ssh stops the while loop the command is in?

我有这个脚本,它列出了 10 多分钟前在远程磁盘上修改过的文件,在本地检索它们,然后应该在远程删除它们。 当我不删除文件时,该脚本有效。 一旦我添加了删除文件的行,循环只被处理一次(只有一个文件被成功复制,并且我有消息确认它在本地磁盘中),然后循环停止而没有任何错误消息。 拜托,知道为什么吗?

#!/bin/bash

S_ACCOUNTS=('yohplala')
RMT_IP='88.214.320.588'
LOC_PATH_DATA='../data/cs_remote/'
MOD_TIME='+10'                      # Last modification time, in minutes

# List, copy, delete files.
for serv_account in "${S_ACCOUNTS[@]}"; do
    while IFS= read -r -d $'[=10=]' file; do
        scp -i ~/.ssh/id_rsa root@$RMT_IP:"$file" "$LOC_PATH_DATA""$serv_account"
        if test -f "$LOC_PATH_DATA""$serv_account"'/'"$(basename "$file")"; then
            echo "$(basename "$file")"' successfully copied.'
            ssh root@$RMT_IP "rm $file"                          # <= troublesome line here
        fi
    done < <(ssh root@$RMT_IP "find "/root/test" -maxdepth 1 -type f -mmin $MOD_TIME -print0")
done

默认情况下,ssh 从您的输入文件 stdin 读取,ssh 消耗文件的其余部分,您的 for 循环终止。

为防止这种情况发生,请将 -n 选项传递给您的 ssh 命令,使其从 /dev/null 而不是 stdin 读取。

来自 ssh 手册页:

-n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The ssh program will be put in the background. (This does not work if ssh needs to ask for a password or passphrase; see also the -f option.)

查看此 thread 了解更多信息。