The comment about not parsing ls
is right on the money. However, in this narrow instance the problem you have is to do with quoting.
This should work:
if [ "$(ls -A $DIR)" ]
then
echo 'Folder is not empty'
else
echo 'Folder is empty'
fi
But it's really a bad way to solve the problem, for multiple reasons.
Here's an alternative (copious others are bound to exist):
if find "${DIR}/" -maxdepth 1 -mindepth 1 | head -1 | grep -Eq "^.|^$"
then
echo 'Folder is not empty'
else
echo 'Folder is empty'
fi
The theory here being that the head -1
will cease the pipeline as soon as we discover a single entry, which should save some time in the event the directory has a lot of entries.
The grep -q "^.|^$"
just confirms that something (or an empty line) was returned by the preceding commands.
Or...
Another way would be to look at the number of "links" the directory has. Any empty directory has exactly 2; one each for the special .
and ..
entries.
GNU stat
if stat --printf %h "${DIR}/" | grep -qvFx 2
then
echo 'Folder is not empty'
else
echo 'Folder is empty'
fi
MacOS native stat
if stat -f %l "${DIR}/" | grep -qvFx 2
then
echo 'Folder is not empty'
else
echo 'Folder is empty'
fi
Both of these assume that either the OS or filesystem will block directory hard linking and report two links when empty, if one or more of these are not the case, the find
solution would be the better choice.
ls
(and what to do instead)?. The short answer from that link is that the output ofls
is programmed for human readability, not script readability. – Thegs Feb 23 '22 at 21:23