I want to delete empty directories without using find
command find . -empty -type d -delete
. like the following:
if [ "$(ls -d *)" ]; then
echo "Not Empty"
else
echo "Delete"
fi
How do I delete empty directories only using ls
?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityrmdir
will delete empty folders (while leaving other folders alone), so you can use something like:
rmdir */
Or, if you're using bash 4+ and you want recursiveness (other shells have other names for the same thing):
shopt -s globstar
rmdir **/
This will give you a lot of error messages, however (one for every non-empty folder).
ls
?
Sep 15, 2014 at 2:02
globstar
. It doesn't traverse dfs, so if you /foo/foo1/foo2
, and none of the dirs contain anything else, it will delete foo2,
but fail for the others. rmdir **/
is also rather likely to hit ARG_MAX
and fail for a tree of reasonable size. Also may want to turn dotglob
on if you want hidden directories.
find
and do something with those files, you should either useglobstar
(bash 4+) or recursion. And since I don't think you can make globstar run in DFS order, you would pretty much be limited to recursion.