eventi
eventi

Reputation: 87

Delete all but the 4 newest directories

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

Upvotes: 4

Views: 674

Answers (4)

Leigh Caldwell
Leigh Caldwell

Reputation: 11066

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

Edit: added 'a' argument to ls

Upvotes: 9

mdxi
mdxi

Reputation: 129

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

Upvotes: 0

mana
mana

Reputation: 6547

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 ;) )

Upvotes: 1

Alexey Feldgendler
Alexey Feldgendler

Reputation: 1800

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.

Upvotes: 1

Related Questions