0

Below keeps latest 10 directories and delete the rest. Works fine with bash.

What would be TCSH equivalent to bash below?

keep = 10
rm -r $(ls -dt */ | tail -n +$((keep+1))) 
2
  • 1
    I doubt that would work in bash as assignments can't have spaces around the = sign. Also, it would surely fail for any directories that have spaces, tabs or newlines in their name, or that have names starting with dashes. It would be safer to do in in zsh with rm -r -- *(/om[11,-1]) or similar.
    – Kusalananda
    Commented Apr 27, 2023 at 13:49
  • 1
    Also, when deleting directories based on the timestamp on the directory, you know that the directory's timestamp does not update unless a directory entry is added or removed in that directory? Updating a file won't update the timestamp, and adding or removing things in a subdirectory also won't update the timestamp on the top-level directory.
    – Kusalananda
    Commented Apr 27, 2023 at 13:55

1 Answer 1

2
set keep = 10
@ tail = $keep + 1
rm -rf -- "`ls -dt -- */ | tail -n +$tail`"

Would be close to what you want, only failing if there are directories (or symlink to directories) whose name contains newline characters but would be at least much more reliable that that very buggy bash code of yours.

As Kusalananda said in comment, zsh would be a much more appropriate shell for that:

keep=10
rm -rf -- *(/om[keep+1,-1])

In any case, the modification time of a directory only reflects when an entry was last added, removed or renamed within (not in subdirectories), so it's not a metric of the age of the data in there and should generally not be used as the basis for deletion.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .