1

I have below directory structure.

drwxr-xr-x 5 ec2-user ec2-user 4096 May 22 07:03 TEEST  
drwxr-xr-x 5 ec2-user ec2-user 4096 May 24 05:33 BEE-TES  
drwxr-xr-x 5 ec2-user ec2-user 4096 May 24 10:53 ONE  
drwxr-xr-x 5 ec2-user ec2-user 4096 May 25 09:50 TWO  
lrwxrwxrwx 1 ec2-user ec2-user   28 May 25 09:50 previous -> TWO  
drwxr-xr-x 5 ec2-user ec2-user 4096 Jun  1 11:00 TEMP  
lrwxrwxrwx 1 ec2-user ec2-user   28 Jun  1 11:00 Current -> TEMP

How to keep or preserve only the last two directories which are modified recently including the symlinks and their respective directories pointed to them?

I have tired the solution in this post How to delete all directories except directories pointed by symlink

but that one is even deleting the directories pointing to symlink only keeping the broken symlink.

Thanks in advance.

0

It is considered bad form to parse the output of ls, but if you use normal filenames, you could try it this way:

#!/bin/bash
qty_keep=2

count=0

ls -t | while read name ; do
if [ $count -lt $qty_keep ] ; then
    if [ -d "$name" ] ; then
        count=$((count+1))
        echo "Keeping dir nr $count: $name"
    else
        echo "$name is not a dir; skipping"
    fi
else
    if [ -d "$name" ] ; then
        count=$((count+1))
        echo "Removing dir nr $count: $name"
        # rm -rf "$name"
    else
        echo "$name is not a dir; skipping"
    fi
fi

As you may have guessed, this will do nothing until you un-comment the rm line, but you should try it as a first dry-run with the comment to see that it does what you want.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.