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 ?
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: