Shell script to count files, then remove oldest files

后端 未结 11 2217
眼角桃花
眼角桃花 2021-01-30 05:29

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 fi

11条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 05:49

    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

提交回复
热议问题