How to delete all subdirectories except a few?

64 Views Asked by At

Using Ansible, I need to ensure, all of the subfolders of a certain directory do not exist except for a few, that must be retained.

The list to be kept will be specified externally -- say, as subfolders_to_keep.

The only way I can see is to first use the find-module to enumerate the subdirectories, and then, using file, delete all, that aren't exceptional -- in a loop.

That would be a fairly long loop here — of the 50-plus entries, only 4 are to survive. Perhaps, there is a more elegant way?

1

There are 1 best solutions below

0
U880D On

That would be a fairly long loop here

Right, with significant performance effects. See in example Ansible: How to optimize running speed of a playbook? or How do I optimize performance of Ansible playbook?

There is a more elegant way?

Since there is no out-of-box module available for such kind of tasks, in your specific Use Case