linux脚本查找早于x天的文件并删除

时间:2016-01-13 09:36:40

标签: linux bash file

你好我有脚本问题,我想删除超过7天的文件,但我做错了:)但是不起作用。提前感谢您的帮助

 #!/bin/bash

# sudo apt-get install pydf
#pydf

# source 
DST="/mnt/share/backup"

#find TIF
FINDFILE=*.TIF


if ! [ -f "$DST/$FINDFILE" ]; then
    echo "no file in: $DST"
    find $DST -type f -mtime +7 -name '*.TIF'
    if ! [ "$?" = "0" ]; then
       echo "ERROR  $DST/"
       exit 200
    fi
else    
    echo "file exist"
    echo "older than 7 days wiil deleted "

    find $DST -type f -mtime +7 -name '*.TIF' -execdir rm -- {} \;
    if ! [ "$?" = "0" ]; then
       echo "ERROR : $DST"
       exit 200
    fi
fi

如果存在文件剂量,则find $DST -type f -mtime +7 -name '*.TIF'如果存在find $DST -type f -mtime +7 -name '*.TIF' -execdir rm -- {} \;

OUTPUT终端

root@fmx2-virtual-machine:/home/fm-x2# ./find.sh
no file in: /mnt/share/backup
/mnt/share/backup/P1010007.TIF
/mnt/share/backup/P1010004.TIF
/mnt/share/backup/P1010003.TIF
/mnt/share/backup/P1010009.TIF
/mnt/share/backup/P1010008.TIF
/mnt/share/backup/P1010005.TIF
/mnt/share/backup/P1010006.TIF

root@fmx2-virtual-machine:/mnt/share/backup# ls -lh
razem 224M
-rw-r--r-- 1 fm-x2 fm-x2 82M sty 13 09:37 2016-01-13.backup.tar.bz2
-rwxr-xr-x 1 fm-x2 fm-x2 21M gru 31  2004 P1010003.TIF
-rwxr-xr-x 1 fm-x2 fm-x2 21M gru 31  2004 P1010004.TIF
-rwxr-xr-x 1 fm-x2 fm-x2 21M gru 31  2004 P1010005.TIF
-rwxr-xr-x 1 fm-x2 fm-x2 21M gru 31  2004 P1010006.TIF
-rwxr-xr-x 1 fm-x2 fm-x2 21M gru 31  2004 P1010007.TIF
-rwxr-xr-x 1 fm-x2 fm-x2 21M gru 31  2004 P1010008.TIF
-rwxr-xr-x 1 fm-x2 fm-x2 21M gru 31  2004 P1010009.TIF
root@fmx2-virtual-machine:/mnt/share/backup# 
如果没有tiff退出,

开头是错误if ! [ -f "$DST/$FINDFILE" ]; then

问题已解决

13行if ! [ "$DST/$FINDFILE" ]; then

root@fmx2-virtual-machine:/home/fm-x2# ./find.sh
file exist
older than 7 days wiil deleted 

root@fmx2-virtual-machine:/mnt/share/backup# ls -l
razem 83536
-rw-r--r-- 1 fm-x2 fm-x2 85538248 sty 13 09:37 2016-01-13.backup.tar.bz2

1 个答案:

答案 0 :(得分:-1)

您可以使用find和piping执行此任务:

find path/to/directory -time +7 | xargs rm