You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

含rsync命令的Bash while循环仅执行一次问题求助

问题解决:while循环配合rsync仅执行一次的问题

问题背景

我有一个包含空格的文件列表/.shareLIST,内容如下:

$ cat /.shareLIST
Archive 1
Archive 2
Archive 3
Archive 4

编写了如下Bash while循环脚本:

while read share
do
    echo $share
    rsync -Hauv -h -P $server:"$share" $destination/
done < /.shareLIST

执行时发现循环仅运行一次(而非预期的四次),同时观察到rsync会启动ssh进程:

# ps -C ssh -o cmd=
ssh -l user mySERVER rsync --server --sender -vulHogDtpre.iLsfxC .......
#

已知在while循环中使用ssh时需加-n参数,但这里没有显式调用ssh,看到有建议给rsync命令追加< /dev/null避免占用标准输入,请问该如何处理?

原因分析

rsync通过ssh连接远程服务器时,会默认继承当前脚本的标准输入(也就是/.shareLIST)。第一次循环时,rsync会把文件里剩下的所有行都读取并消耗掉,导致read命令再也读不到后续行,循环因此提前终止。

解决方法

方法1:给rsync命令追加< /dev/null

直接让rsync从空设备读取输入,避免占用循环的标准输入,修改后的脚本如下:

while read share
do
    echo $share
    rsync -Hauv -h -P $server:"$share" $destination/ < /dev/null
done < /.shareLIST

方法2:指定rsync使用带-n参数的ssh

因为rsync默认用ssh作为传输协议,所以可以通过-e参数指定ssh命令并加上-n,让ssh不从标准输入读取内容:

while read share
do
    echo $share
    rsync -Hauv -h -P -e 'ssh -n' $server:"$share" $destination/
done < /.shareLIST

方法3:使用独立的文件描述符供循环读取

把文件列表的输入重定向到非标准文件描述符(比如3),让循环从这个描述符读取内容,不与rsync的标准输入冲突:

while read -u 3 share
do
    echo $share
    rsync -Hauv -h -P $server:"$share" $destination/
done 3< /.shareLIST

内容的提问来源于stack exchange,提问作者SebMa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 06:15:02