I am trying to write a shell script to delete all the sub directories in a given directory. I know there is an easy approach for the same.
Like doing this
find ./ -type d -exec rm -r {} \;
but since I am learning shell scripting so I prefer to write a script for the same. Here is my approach
for i in `ls ./*`; do
if [ -d $i ];then
rm -r $i
fi
done
When I run this script this gives me following errors
rm: cannot remove directory: `.’
after giving this error this stops.So what is the error in my approach.As far as I understand blank names should create some problem. But this script has failed to go that far.
The ls ./* makes a list of all the files in each immediate subdir of . The -d then checks the name of the file but as if it was in . not the subdir it comes from.
For example if you had:
then ls ./* would make a list of bar and baz, as the ./* would match foo1 and foo2 and ls would then list the contents of each of those 2 directories.
The error message you are getting is probably because your ls has been aliased to be ‘ls -a’ which lists . and .. As the answer by Florin says, you can use ls -A ./* to avoid that issue.
If you just want to delete the directories in ., just do: