[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Bash script last 4 folder delete



On Tue 12 Oct 2021 at 17:41:59 (+0300), Gokan Atmaca wrote:
> 
> I have directories created at different times. This last updated
> directory is in the directory with a symbolic link named "last".
> Directories are named from 100 to 110. what i want is to delete all
> directories except the folder named "last" and 4 before it. How can I
> do that?
> 
> Exampe_folder_list:
> 100
> 101
> 102
> 103
> 104
> 105
> 106
> 107
> 108
> 109
> 110
> last -> /root/test1/110
> 
> 
> How can I do that?

You could "find" the directories concerned, "sort" by some criteria
(name, or time etc), use "head --lines=-5" to drop the last five lines,
and "rmdir/rm" to remove any remaining in the list.

For fewer processes, you could do a similar set of operations in
shell by constructing an array, removing five elements, and using
any remaining elements to remove the directories (and their contained
files) in the same manner.

Remember to deal with the symlink in whatever manner you choose
(check it, ignore it, etc).

Before I actually used either method, I would test it with "echo"
or "mv -i" rather than removing anything, and before I attempted
the latter, I would refresh my recollections of these pages:

https://mywiki.wooledge.org/BashGuide/Arrays
https://www.tldp.org/LDP/abs/html/arrays.html

BTW your Subject line implies the opposite.

Cheers,
David.


Reply to: