We have a Linux directory where files and directories are being added to it daily.

We like to control this list of files and subdirectories in the directory by fixing the list to 50 most recent files and directories at any given time.

How do we write a script to achieve this goal?

  • What does "fixing the list to 50 most recent files" mean, exactly? – slhck Apr 3 '13 at 9:17
  • Do you want to list the 50 most resent files? Or delete all files older than that? – Ярослав Рахматуллин Apr 4 '13 at 3:24
  • Hi Ярослав Рахматуллин, slhck, thanks for responding. We like to keep the most recent 50 subdirectories of a directory. – chz Apr 5 '13 at 13:54
  • @chz do you mean that you want to delete all directories except for the 50 most recently created ones? – evilsoup Apr 9 '13 at 20:41

With GNU find and sort, this gets you the 50 latest files and their timestamp from the current directory:

find . -mindepth 1 -maxdepth 1 -printf '%T@ %p\n' | sort -n | tail -n 50

Pipe these into while read to get each filename:

find . -mindepth 1 -maxdepth 1 -printf '%T@ %p\n' |
sort -n | tail -n 50 |
while read -r ts file; do echo rm -rf -- "$file"; done

Here, printf outputs a sortable timestamp, which the numeric sort will use. We get the oldest 50 files or directories and remove each one individually. Remove the echo in the script to actually execute the commands.

Note that this does not work if your files/directories contain a newline in their name. Doesn't happen that often, but be careful to check. Due to the nature of read, it will also not work if there are leading or trailing spaces.

For some more ideas, see: BashFAQ/003 – How can I find the latest (newest, earliest, oldest) file in a directory?

  • The question was how to keep the newest 50 files, not how to remove 50 oldest ones... – ak1ra Dec 22 '20 at 16:18

If you need to look only at the dirs in the folder (not for subdir) then execute the script:

l=$(ls |wc -l)
rm -rf `ls -1t|tail -$n`
  • 1
    Please carefully read mywiki.wooledge.org/ParsingLs — the output of ls shouldn't be parsed. This will cause problems with files containing spaces in their path. Your script is therefore not safe. Also, for the future, please check our formatting help and indent code by 4 spaces. – slhck Dec 23 '13 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.