检查文件夹中的特定文件是否存在于另一个文件夹中 - Shellscript

时间:2015-10-08 22:58:07

标签: shell

我开始shellcripting,我遇到了脚本问题。 所以,我有两个folers(与我在其中的文件类型无关),我需要检查文件夹1上的文件是否存在于文件夹2中。如果有,请检查其修改日期是否更新。

这就是我所拥有的:

#!/bin/sh

for i in `find $1 -type f`
do
    for j in `find $2 -type f`
    do
        if [ -e $2/$i ]
        then
            if [ $i -ot $j ]
            then
                echo File "`basename $i`" its newer and it will be copied
            else
                echo File is updated
            fi
        else
            echo "`basename $i`" will be copied because it doesn't exist
        fi
    done
done

$ 1和$ 2是文件夹参数

提前致谢

编辑:

在文件夹1中有3个文件,在文件夹2中有一个文件(文件2)。

我在folder1中有3个文件,其中一个也在folder2中,我得到了(file2在两个文件夹中):

file1 will be copied because it doesn't exist
file2 will be copied because it doesn't exist
file2 will be copied because it doesn't exist
file1 will be copied because it doesn't exist
file3 will be copied because it doesn't exist
file3 will be copied because it doesn't exist

1 个答案:

答案 0 :(得分:0)

该脚本有两个问题: A.你不需要嵌套for循环,因为你正在对第一个目录中的每个文件进行一些检查,而不是对第一个目录中的每个文件和scond目录中的每个文件进行检查(这就是为什么你这样做的原因)显示的文件很多)。 B.当你使用find来获取目录中的文件时,你不需要路径,只需要文件名,你将在第二个目录中检查它。

这是固定版本。让我知道是否能解决您的问题。

#!/bin/bash

for i in `find $1 -type f -printf "%f\n" | sort`;
do
  if [ -e "$2/$i" ]
  then
    if [ "$1/$i" -ot "$2/$i" ]
    then
      echo "File basename $i its newer and it will be copied"
    else
      echo "File is updated"
    fi
  else
    echo "basename $i will be copied because it doesn't exist"
  fi
done
相关问题