Evan_HZY
Evan_HZY

Reputation: 1024

linux ksh how to remove all directories except the latest some directories

I am using Linux ksh to remove some old directories that I don't want.

What I use is this:

   #! /bin/ksh
   OLD=/opt/backup
   DIR_PREFIX="active"
   DIRS=$(ls ${OLD} -t | grep ${DIR_PREFIX})
   i=0
   while [[ $i -lt ${#DIRS[*]} ]]; do
       if [ $i -gt 4 ];
      then
          echo ${DIRS[$i]}
          ((i++))
      else
          ((i++))
      fi
  done

what I am trying to do is: to store a list all the directories sorted by time into a variable-I assume it would be an array but somehow the size of it is 1... ..., then in the while loop, if the position of the directory is greater than 4, then I print out the directory name.

Any idea of how to

Upvotes: 2

Views: 308

Answers (2)

William Pursell
William Pursell

Reputation: 212248

If all you want is to print all but the first four entries, just pipe it to head or sed:

#!/bin/sh
OLD=/opt/backup
DIR_PREFIX=active
ls $OLD -t | grep $DIR_PREFIX | sed 1,4d | while read DIR; do
    echo $DIR;
done

If you are just using echo, the while loop is redundant, but presumably you will have more commands in the loop.

Upvotes: 1

Evan_HZY
Evan_HZY

Reputation: 1024

OLD=/opt/backup
DIR_PREFIX="active"
DIRS_RESULT=$(ls ${OLD} -t | grep ${DIR_PREFIX})
i=0
for DIR in ${DIRS_RESULT}
    do
        if [ $i -gt 4 ];
        then
            echo ${DIR}
            rm -rf ${DIR}
            ((i++))
        else
            ((i++))
        fi
    done

this one works for me

Upvotes: 0

Related Questions