从两个方向遍历文件列表

Iterate through filelist from two directions

我有以下 bash 脚本

#!/bin/bash 


for i in `ls /file-directory/ | grep -v static-backup | grep -v fileGroup1 | grep -v fileGroup2`
 do
 echo $i
 rsync --delete -avz --size-only --exclude "$i/stuff1" --exclude "$i/stuff2" --exclude "$i/stuff3" --exclude "$i/stuff4" --exclude "$i/stuff5" --exclude "$i/stuff6" /file-directory/$i otherServer:/file-directory/ && echo " exit code: " $?" $i" || echo " exit code: " $?" $i"
 done

脚本遍历文件目录并同步其子目录,排除某些文件组和这些文件组目录的部分内容。我希望此脚本产生两个 rsync 作业,一个从目录顶部开始,另一个从底部开始。他们会朝相反的方向迭代并在中间相遇。

这对于正常的循环计数来说相对简单,并且在 python 之类的事情中不会太难(您可以将目录数保存为变量,然后使用该变量进行迭代).我怎样才能在 bash 中做类似的事情?

你可以利用&中的bashfork一个过程。甚至循环。 我相信有不止一种方法可以实现这一点,但这是一种方法。

伪代码

获取两个单独数组中的文件列表,这样它们每个都包含列表的一半(偶数)。
对于奇数文件,第二个数组将包含一个文件。
遍历第一个数组并使用 &
分叉一个进程 使用 &

遍历第二个数组并分叉第二个进程

代码

#!/bin/bash
dir_len=$(ls /file-directory/ |wc -l|awk '{print $NF}')
midpoint=$(($dir_len / 2))

array1=()
array2=()
count=0

#Loop through files and divide contents into two arrays  
for i in $(ls /file-directory/)
do
  count=$(($count + 1))
  if [ $count -le $midpoint ] ; then
    array1+=($i)
  elif [[ $count -gt $midpoint && $count -le $dir_len ]] ; then
    array2+=($i)
  fi
done

#Loop through first array and fork     
for i in "${array1[@]}"
do
  echo $i
  #your rsync command here
done&

#Loop through second array and fork
for j in "${array2[@]}"
do
  echo $j
  #your rsync command here
done &  

注:
& 在第二个 for 循环中是可选的,因为你可以 运行 它在前台,因为只有两个进程。
此外,您可能希望针对不需要的文件或文件夹为空时强化脚本。

编辑。

根据您需要 rsync 的文件类型,请参考此 link 获取灵感,而不是使用“ls /folder_name/”。

https://unix.stackexchange.com/questions/9496/looping-through-files-with-spaces-in-the-names