Delete all but the 4 latest directories

I want to delete all but 4 of the latest directories in the parent directory. How do you do it in Bash?

+4
source share
4 answers
ls -atrd */ | head --lines=-4 | xargs rm -rf 

Edit: added argument 'a' to ls

+9
source

Please explain whether you want to “delete all directories except four new ones” or “delete all (files and directories), except for the four newest directories”.

Also note that the creation time is unknown for directories. You can only indicate when the directory was last modified, that is, files were added, deleted or renamed.

+1
source

you can do the following:

 #!/bin/bash #store the listing of current directory in var mydir=`ls -t` it=1 for file in $mydir do if [ $it -gt 5 ] then echo file $it will be deleted: $file #rm -rf $file fi it=$((it+1)) done 

(remove # before rm to make this happen;))

+1
source

Another BSD-safe way to do this is with arrays (why not?)

 #!/bin/bash ARRAY=( `ls -td */` ) ELEMENTS=${#ARRAY[@]} COUNTER=4 while [ $COUNTER -lt $ELEMENTS ]; do echo ${ARRAY[${COUNTER}]} let COUNTER=COUNTER+1 done 
0
source

Source: https://habr.com/ru/post/1276747/


All Articles