复制文件(如果存在)在bash中跳过

时间:2016-11-29 15:55:23

标签: bash loops unix

我想首先检查源位置上的文件是否属于日期范围:如果是,则复制else跳过并检查下一个文件。 有人可以帮助我这样做,因为我是shell脚本的新手。

1 个答案:

答案 0 :(得分:2)

find已经只返回已存在的条目;那里没有问题,但你用来迭代结果的代码严重受损。

这里的问题不是跳过,而是一般的语法正确,(其次)与正确性相关的做法。即使您修复了原始代码中最直接的错误,也会与BashPitfalls #1DontReadLinesWithFor发生冲突。

有关使用find的最佳做法的完整讨论,请参阅UsingFind。也就是说,正确的方法之一是:

#!/bin/bash
#      ^^^- important: not /bin/sh

while IFS= read -r -d '' filename; do
  mv "$filename" /to_path
done < <(find filedirectory_path/ -type f -newermt "$date1" ! -newermt "$date2" -print0)

...或...

find filedirectory_path/ -type f -newermt "$date1" ! -newermt "$date2" -exec mv '{}' /to_path \;