0

I am writing a backup programm, and I need to execute a bash command to delete the oldest directory in a specific directory.

I have found this command to print the oldest directory:

find -type f -printf '%T+ %p\n' | sort | head -n 1

And this command to delete a directory and all its content:

rm -rf [oldest directory name]

How can I combine between these two in order to delete the oldest folder?

2
  • -type f finds only files, not directories.
    – l0b0
    Jul 9, 2014 at 14:36
  • Do you mean the oldest among the direct subdirectories only, or also among the indirect subdirectories? Feb 6, 2017 at 14:23

1 Answer 1

0

This should work with any path (Thanks to @StéphaneChazelas for the head trick) and should be POSIX compatible (formatted for readability):

printf %q "$(
    find . -type d -printf "%T+ %p\0" |
    tr '\0\n' '\n\0' |
    sort |
    head -n 1 |
    tr '\0\n' '\n\0' |
    sed -e 's/^[^ ]\+ //')"

To actually remove the directory, replace printf %q with rm -rf --

7
  • after executing the first line the bash says date_and_path command not found
    – itaied
    Jul 10, 2014 at 7:24
  • Not in Bash 4, if you copy the command verbatim. date_and_path is not a command, but a variable which you then use in the next line.
    – l0b0
    Jul 10, 2014 at 8:11
  • Is there other way to execute this command without using the var date_and_path? Something like: rm -rf -- find . -type d -printf "%T+ %p\0" | tr '\0\n' '\n\0' | sort | head -n 1 | tr '\0\n' '\n\0'
    – itaied
    Jul 10, 2014 at 8:29
  • Done. You have to use a more complicated way to remove the datetime at the start in this case.
    – l0b0
    Jul 10, 2014 at 8:37
  • Thanks for your response, but when running this command in shell, I don't get any error, but it also doesn't delete any file. Any suggestions?
    – itaied
    Jul 10, 2014 at 9:16

You must log in to answer this question.

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