首页 > 解决方案 > 使用 mapfile 调用 rsync

问题描述

使用以下 bash 代码来处理随 mapfile 随机传递的文件名。我想调用rsync每个文件并发送到目标路径dpath

mapfile -d '' fl < <(
  find "$dpath" -maxdepth 1 -type f "${inclnm[@]}" |
  shuf -z -n "$nf"
)

或者shuf直接处理参数

mapfile -d '' fl < <( shuf -z -n "$nf" -e "${inclnm[@]}" )

如何修改两个替代方案以rsync在每个文件上运行并发送到目的地?

标签: bashrsyncmap-files

解决方案


正如评论中所说,您不需要mapfile中间数组。只需流式传输以空分隔的文件选择,rsync如下所示:

#!/usr/bin/env bash

nf=4
inclnm=( a* b* )
# For testing purpose, destination is local host destfolder inside
# user home directory
destination="$USER@localhost:destfolder"

# Pipe the null delimited shuffled selection of files into rsync 
shuf -z -n "$nf" -e "${inclnm[@]}" |
# rsync reads the null-delimited selection of from files from standard input
rsync -a -0 --files-from=- . "$destination"

如果您想收集随机选择的文件并使用它,rsync请执行以下操作:

#!/usr/bin/env bash

nf=4
inclnm=( a* b* )
# For testing purpose, destination is local host destfolder inside
# user home directory
destination="$USER@localhost:destfolder"

# Capture the selection of files into the fl array
mapfile -d '' fl < <( shuf -z -n "$nf" -e "${inclnm[@]}" )

# Pass the fl array elements as sources to the rsync command
rsync -a "${fl[@]}" "$destination"

推荐阅读