0

I have a function and I want to delete the files in a directory. It does the desired work, like if i want to delete from abc/xyz/p.txt Then it will delete p.txt. But if I want to delete abc/xyz/x.txt then It does not delete x.txt because the name starts with x and the directory it resides is also starting with x.

Below is the code-

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
}
  • Your example code is complicated and incomplete. What is `FILE_DIR`? what is `FILE_NAME_PREFIX`? – Beta Mar 23 '18 at 14:58

1 Answers1

0

From find man page:

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

Now, if you make FILE_NAME_PREFIX='x' then find will not process xyz because it matches ${FILE_NAME_PREFIX}*.

so, -prune is overriding your -type f default action which is -print. Try removing prunesince you already instructed to find files only.

This question has more info.

Luis Muñoz
  • 5,935
  • 2
  • 20
  • 38