Achilles
Achilles

Reputation: 741

Removing directory recursively without using rm command

Hi I am trying to remove/delete a directory along with its sub directories and files recursively. I don't want to use rm -r. I have come up with the following code.

 function recursive(){
            for i in "$1"/*; do

                    if [ -d $i ];then
                            echo "FILE $i IS A DIRECTORY"
                            if [ "$(ls -A $i)" ];then
                                    echo "DIRECTORY IS NOT EMPTY CALLING RECURSIVE AGAIN"
                                    recursive $i
                            else
                                    echo "DELETE THIS DIRECTORY: ITS EMPTY"
                            fi
                    elif [ -e $i ];then
                            echo "DELETING FILE $i"
                    else
                            echo UNKNOWN FILE $(basename $i)
                    fi
            done

    }

The problem is as I dig deep into sub directories, I can delete their files on the way, but once I reach the bottom of directory tree, I have to delete all the directories which are now empty (maybe on my way back up?)

Would really appreciate if someone could help me with its logic or guide me in the right direction.

The answer to THIS question makes sense but I don't know how can it handle if there are few levels of sub directories ?

Upvotes: 2

Views: 1387

Answers (2)

Marten
Marten

Reputation: 1356

After you have deleted the contents of a directory you can delete it in any case. So just remove the else statement and move the remove-directory-command one level up:

function recursive(){
        for i in "$1"/*; do

                if [ -d $i ];then
                        echo "FILE $i IS A DIRECTORY OR A (SYM)LINK TO ONE"
                        if [ "$(ls -A $i)" ];then
                                echo "DIRECTORY IS NOT EMPTY CALLING RECURSIVE AGAIN"
                                recursive $i
                        fi

                        echo "DELETE THIS DIRECTORY: ITS (NOW) EMPTY"
                elif [ -e $i ];then
                        echo "DELETING FILE $i"
                else
                        echo UNKNOWN FILE $(basename $i)
                fi
        done

}

Upvotes: 2

sehe
sehe

Reputation: 393154

I would simply use

find "$1" -delete

unlink is probably a nice thought too, but I'm not sure whether you'd consider that cheating :)

Upvotes: 4

Related Questions