6

I have a directory. It is empty. If i perform ls -lrt , it shows total 0

How do I specify an If condition to perform something, only if the directory is empty.

I mean to ask how to capture that 0 value.

Community
  • 1
  • 1
Animesh
  • 176
  • 1
  • 1
  • 10
  • 2
    See: [Bash checking if folder has contents](http://stackoverflow.com/q/20456666/3776858) and [Checking from shell script if a directory contains files](http://stackoverflow.com/q/91368/3776858) – Cyrus Mar 27 '16 at 08:19
  • @Cyrus I checked those too, but I can't seem to work it out. – Animesh Mar 27 '16 at 08:23

2 Answers2

13

From here. This should help you run your statements within the if else loop. I saved the DIR in the variable

#!/bin/bash
FILE=""
DIR="/empty_dir"
# init
# look for empty dir 
if [ "$(ls -A $DIR)" ]; then
     echo "Take action $DIR is not Empty"
else
    echo "$DIR is Empty"
fi
# rest of the logic
saan
  • 333
  • 3
  • 9
-3

Remove the -A option :

$ mkdir /tmp/aaa
$ ls /tmp/aaa
$ a=\`ls /tmp/aaa`
$ [[ -z $a ]]
$ echo $?
0
SLePort
  • 15,211
  • 3
  • 34
  • 44
whogiawho
  • 466
  • 9
  • 21