Question

I want to delete all but the 4 newest directories in my parent directory. How would you do this in Bash?

Was it helpful?

Solution

ls -atrd */ | head --lines=-4 | xargs rm -rf

Edit: added 'a' argument to ls

OTHER TIPS

Please clarify if you mean “delete all directories but the four newst ones” or “delete everything (files and directories) except for the four newest directories”.

Please also note that creation times are not known for directories. One can only tell when a directory was last modified, that is, had files added, removed or renamed.

you could 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 the # before rm to make it really happen ;) )

Another, BSD-safe, way to do it, 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top