please check this code

hi,
i m checking the directory is empty or not

  FILE=""
  DIR="/ann/a1"

if [ "$(ls -A $dir)" ]; then
       echo "$dir is not Empty"
  else
      echo "$dir is Empty"
  fi

i m always getting this directory is not empty, even if the directory is empty

please point where i had went wrong??

FILE=""
DIR="/ann/a1"

if [ -z "$(ls -A $DIR)" ]; then
echo "$dir is not Empty"
else
echo "$dir is Empty"
fi

hi ,
now im getting only dir is empty.... for what ever condition.....

when ever i had cehcked this line ls -A $dir
its giving me the error like this directory not accessible :frowning:

regards
Angel

Couple of issues here.
1) Environment Variable names are case-sensitive. $DIR and $dir are not the same variable.
2) Your messages appear to be the wrong way round. When we find no files (and the -z condition is satisfied) our message should be "Empty".

FILE=""
dir="/ann/a1"

if [ -z "$(ls $dir)" ]; then
     echo "$dir is Empty"
else
     echo "$dir is not Empty"
fi
1 Like

There's no need of process substitution : (just take care that the condition is reverted)

dir="/ann/a1"
if ls $dir; then
     echo "$dir is not Empty"
else
     echo "$dir is Empty"
fi

This is wrong : -z is true if empty
so... it should be

if [ -z "$(ls -A $DIR)" ]; then
echo "$dir IS Empty"
else
echo "$dir is NOT Empty"
fi

or

if [ -n "$(ls -A $DIR)" ]; then
echo "$dir is not Empty"
else
echo "$dir is Empty"
fi
emptydir() { set -- "$1"/*; ! [ -e "$1" ] ;}
if emptydir "$DIR"; then
  echo "dir is Empty"
else
  echo "dir is not Empty"
fi