无法删除共享相同前缀名称的目录中存在的文件

时间:2018-03-23 14:14:48

标签: shell unix sh

我有一个功能,我想删除目录中的文件。 它可以完成所需的工作,就像我要从abc/xyz/p.txt中删除一样,然后它会删除p.txt。 但是,如果我要删除abc/xyz/x.txt,那么它不会删除x.txt,因为名称以x开头,而它所在的目录也以x开头。

以下是代码 -

fn_DeleteFiles()
{
set -x
    fn_Log ${INFO} "Deleting the files older the Retention Period days"
    if [ 0 -eq `find ${FILE_DIR} -mtime +${RETENTION_DAYS} -type f -name "${FILE_NAME_PREFIX}*" | wc -l` ]
    then
        fn_Log ${INFO} "There are no files in the file directory older than ${RETENTION_DAYS} days."
    else
        # Deleting the files older than Purge days and Invoke fn_Log() function to log the file name in the log file
        find ${FILE_DIR} -prune -name "${FILE_NAME_PREFIX}*" -type f -mtime +${RETENTION_DAYS} | while read NAME; do echo ${NAME};rm -f ${NAME};
        fn_Log ${INFO} "Deleting file: ${NAME} " ;
        done
        if [ ${?} -ne 0 ]
        then
            fn_Log ${ERROR} "Purging of files in the file Directory ${FILE_DIR} has not completed successfully."
        else
            fn_Log ${INFO} "Purging of files in the file Directory ${FILE_DIR} completed successful"
        fi
    fi
}

1 个答案:

答案 0 :(得分:0)

来自find手册页:

-prune True; if the file is a directory, do not descend into it.

现在,如果您FILE_NAME_PREFIX='x',则find将无法处理xyz,因为它与${FILE_NAME_PREFIX}*匹配。

因此,-prune会覆盖-type f默认操作-print。请尝试删除prune,因为您已指示仅查找文件。

question有更多信息。