Shell script to count files, then remove oldest files

后端 未结 11 2433
眼角桃花
眼角桃花 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条回答
  •  佛祖请我去吃肉
    2021-01-30 05:51

    Try this:

    ls -t | sed -e '1,10d' | xargs -d '\n' rm
    

    This should handle all characters (except newlines) in a file name.

    What's going on here?

    • ls -t lists all files in the current directory in decreasing order of modification time. Ie, the most recently modified files are first, one file name per line.
    • sed -e '1,10d' deletes the first 10 lines, ie, the 10 newest files. I use this instead of tail because I can never remember whether I need tail -n +10 or tail -n +11.
    • xargs -d '\n' rm collects each input line (without the terminating newline) and passes each line as an argument to rm.

    As with anything of this sort, please experiment in a safe place.

提交回复
热议问题