Shell script to count files, then remove oldest fi

2019-03-08 03:07发布

I am new to shell scripting, so I need some help here. I have a directory that fills up with backups. If I have more than 10 backup files, I would like to remove the oldest files, so that the 10 newest backup files are the only ones that are left.

So far, I know how to count the files, which seems easy enough, but how do I then remove the oldest files, if the count is over 10?

if [ls /backups | wc -l > 10]
    then
        echo "More than 10"
fi

标签: linux bash shell
10条回答
三岁会撩人
2楼-- · 2019-03-08 03:50

Straightforward file counter:

max=12
n=0
ls -1t *.dat |
while read file; do
    n=$((n+1))
    if [[ $n -gt $max ]]; then
        rm -f "$file"
    fi
done
查看更多
ら.Afraid
3楼-- · 2019-03-08 03:51
stat -c "%Y %n" * | sort -rn | head -n +10 | \
        cut -d ' ' -f 1 --complement | xargs -d '\n' rm

Breakdown: Get last-modified times for each file (in the format "time filename"), sort them from oldest to newest, keep all but the last ten entries, and then keep all but the first field (keep only the filename portion).

Edit: Using cut instead of awk since the latter is not always available

Edit 2: Now handles filenames with spaces

查看更多
虎瘦雄心在
4楼-- · 2019-03-08 03:52

Experiment with this, because I'm not 100% sure it'll work:

cd /backups; ls -at | tail -n +10 | xargs -I{} "rm '{}'"
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-03-08 03:56

Make sure your pwd is the correct directory to delete the files then(assuming only regular characters in the filename):

ls -A1t | tail -n +11 | xargs rm

keeps the newest 10 files. I use this with camera program 'motion' to keep the most recent frame grab files. Thanks to all proceeding answers because you showed me how to do it.

查看更多
登录 后发表回答