113

I want to test if a directory doesn't contain any files. If so, I will skip some processing.

I tried the following:

if [ ./* == "./*" ]; then
    echo "No new file"
    exit 1
fi

That gives the following error:

line 1: [: too many arguments

Is there a solution/alternative?

19 Answers 19

146
if [ -z "$(ls -A /path/to/dir)" ]; then
   echo "Empty"
else
   echo "Not Empty"
fi

Also, it would be cool to check if the directory exists before.

| improve this answer | |
  • 13
    Don't use && and || simultaneously! If echo "Not Empty" fails, echo "Empty" will run! Try echo "test" && false || echo "fail"! Yes, I know echo will not fail but if you change any other command, you will be suprise! – uzsolt Oct 31 '11 at 9:27
  • 4
    Please, provide at least one example when the code above won't work. Concretely this code is absolutely correct. I hope that asker is able to adapt this for his own purposes – Andrey Atapin Oct 31 '11 at 9:56
  • 4
    where's touch /empty in my line? – Andrey Atapin Oct 31 '11 at 10:01
  • 4
    I had trouble getting this method to work when the /path/to/dir contained spaces and needed to be quoted. I used [ $(ls -A "$path" | wc -l) -ne 0], inspired by @ztank1013's answer. – pix May 19 '15 at 3:23
  • 8
    Oh no! There is a very important problem with this code. It should be if [ -n "$(ls -A /path/to/dir)" ]; then ... Please update the answer before someone pastes this code into their server somewhere and a hacker figures out how to exploit it. If /path/to/dir isn't empty, then the filenames there get passed as arguments to /bin/test which is clearly not intended. Just add the -n argument, problem solved. Thanks! – Edward Ned Harvey Dec 5 '16 at 21:20
27

No need for counting anything or shell globs. You can also use read in combination with find. If find's output is empty, you'll return false:

if find /some/dir -mindepth 1 | read; then
   echo "dir not empty"
else
   echo "dir empty"
fi

This should be portable.

| improve this answer | |
  • Nice solution, but I think your echo calls reflect the wrong result : in my test (under Cygwin) find . -mindepth 1 | read had a 141 error code in a non-empty dir, and 0 in an empty dir – Lucas Cimon Dec 20 '17 at 9:17
  • @LucasCimon Not here (macOS and GNU/Linux). For an non-empty directory, read returns 0, and for an empty one, 1. – slhck Dec 20 '17 at 11:28
  • 4
    PSA does not work with set -o pipefail – Colonel Thirty Two Sep 10 '19 at 2:07
20
if [ -n "$(find "$DIR_TO_CHECK" -maxdepth 0 -type d -empty 2>/dev/null)" ]; then
    echo "Empty directory"
else
    echo "Not empty or NOT a directory"
fi
| improve this answer | |
  • Correct and fast. Nice! – l0b0 Feb 24 '12 at 11:00
  • 4
    It needs quotes (2x) and the test -n to be correct and safe (test with directory with spaces in the name, test it with non-empty directory with name '0 = 1'). ... [ -n "$(find "$DIR_TO_CHECK" -maxdepth 0 -type d -empty 2>/dev/null)" ]; ... – Zrin Mar 7 '17 at 23:51
  • 1
    @ivan_pozdeev That's not true, at least for GNU find. You may be thinking of grep. serverfault.com/questions/225798/… – Vladimir Panteleev Jun 19 '18 at 10:55
  • It might be simpler to write find "$DIR_TO_CHECK" -maxdepth 0 -type d -empty | grep ., and rely on the exit status from grep. Whichever way you do it, this is very much the right answer to this question. – Tom Anderson Jul 6 '18 at 13:56
15
#!/bin/bash
if [ -d /path/to/dir ]; then
    # the directory exists
    [ "$(ls -A /path/to/dir)" ] && echo "Not Empty" || echo "Empty"
else
    # You could check here if /path/to/dir is a file with [ -f /path/to/dir]
fi
| improve this answer | |
  • 4
    That must be it, no need for parsing ls output, just see if it is empty or not. Using find just feels like an overkill to me. – akostadinov Sep 18 '13 at 12:34
4

This will do the job in the current working directory (.):

[ `ls -1A . | wc -l` -eq 0 ] && echo "Current dir is empty." || echo "Current dir has files (or hidden files) in it."

or the same command split on three lines just to be more readable:

[ `ls -1A . | wc -l` -eq 0 ] && \
echo "Current dir is empty." || \
echo "Current dir has files (or hidden files) in it."

Just replace ls -1A . | wc -l with ls -1A <target-directory> | wc -l if you need to run it on a different target folder.

Edit: I replaced -1a with -1A (see @Daniel comment)

| improve this answer | |
  • 2
    use ls -A instead. Some file systems don't have . and .. symbolic links according to the docs. – Daniel Beck Oct 31 '11 at 10:12
  • 1
    Thanks @Daniel, I edited my answer after your suggestion. I know the "1" might be removed too. – ztank1013 Oct 31 '11 at 10:21
  • 3
    It doesn't hurt, but it's implied if output it not to a terminal. Since you pipe it to another program, it's redundant. – Daniel Beck Oct 31 '11 at 10:24
  • 1
    -1 is definitely redundant. Even if ls will not print one item per line when it will be piped then it doesn't affect the idea of checking if it produced zero or more lines. – Victor Yarema Oct 13 '17 at 9:31
4

Using an array:

files=( * .* )
if (( ${#files[@]} == 2 )); then
    # contents of files array is (. ..)
    echo dir is empty
fi
| improve this answer | |
  • 5
    Very nice solution, but note that it requires shopt -s nullglob – xebeche Jan 16 '17 at 11:24
  • 3
    The ${#files[@]} == 2 assumption doesn't stand for the root dir (you will probably not test if it's empty but some code that doesn't know about that limitation might). – ivan_pozdeev Jan 21 '18 at 4:29
  • 1
    @ivan_pozdeev: What do you mean? When I do cd / && files=(* .*), I get an enumeration of all the files and directories in the root directory, which includes . and ... So the ${#files[@]} == 2 test is valid. – Scott Feb 3 at 4:08
4

A hacky, but bash-only, PID-free way:

is_empty() {
    test -e "$1/"* 2>/dev/null
    case $? in
        1)   return 0 ;;
        *)   return 1 ;;
    esac
}

This takes advantage of the fact that test builtin exits with 2 if given more than one argument after -e: First, "$1"/* glob is expanded by bash. This results in one argument per file. So

  • If there are no files, the asterisk in test -e "$1"* does not expand, so Shell falls back to trying file named *, which returns 1.

  • ...except if there actually is one file named exactly *, then the asterisk expands to well, asterisk, which ends up as the same call as above, ie. test -e "dir/*", just this time returns 0. (Thanks @TrueY for pointing this out.)

  • If there is one file, test -e "dir/file" is run, which returns 0.

  • But if there are more files than 1, test -e "dir/file1" "dir/file2" is run, which bash reports it as usage error, i.e. 2.

case wraps the whole logic around so that only the first case, with 1 exit status is reported as success.

Possible problems I haven't checked:

  • There are more files than number of allowed arguments--I guess this could behave similar to case with 2+ files.

  • Or there is actually file with an empty name--I'm not sure it's possible on any sane OS/FS.

| improve this answer | |
  • 1
    Minor correction: if there is no file in dir/, then test -e dir/* is called. If the only file is '*' in dir then test will return 0. If there are more files, then it returns 2. So it works as described. – TrueY Sep 7 '18 at 11:43
  • You're right, @TrueY, I've incorporated it in the answer. Thanks! – Alois Mahdal Sep 11 '18 at 14:45
4

With FIND(1) (under Linux and FreeBSD) you can look non-recursively at a directory entry via "-maxdepth 0" and test if it is empty with "-empty". Applied to the question this gives:

if test -n "$(find ./ -maxdepth 0 -empty)" ; then
    echo "No new file"
    exit 1
fi
| improve this answer | |
  • 1
    It may not be 100% portable, but it's elegant. – Craig Ringer Nov 28 '18 at 2:59
  • This also finishes early in large directories, works with pipefail: set -o pipefail; { find "$DIR" -mindepth 1 || true ; } | head -n1 | read && echo NOTEMPTY || echo EMPTY – macieksk Nov 24 '19 at 12:29
3

Use the following:

count="$( find /path -mindepth 1 -maxdepth 1 | wc -l )"
if [ $count -eq 0 ] ; then
   echo "No new file"
   exit 1
fi

This way, you're independent of the output format of ls. -mindepth skips the directory itself, -maxdepth prevents recursively defending into subdirectories to speed things up.

| improve this answer | |
  • Of course, you're now dependent on wc -l and find output format (which is reasonably plain though). – Daniel Beck Oct 31 '11 at 10:25
3

What about testing if directory exists and not empty in one if statement

if [[ -d path/to/dir && -n "$(ls -A path/to/dir)" ]]; then 
  echo "directory exists"
else
  echo "directory doesn't exist"
fi
| improve this answer | |
1

I think the best solution is:

files=$(shopt -s nullglob; shopt -s dotglob; echo /MYPATH/*)
[[ "$files" ]] || echo "dir empty" 

thanks to https://stackoverflow.com/a/91558/520567

This is an anonymous edit of my answer that might or might not be helpful to somebody: A slight alteration gives the number of files:

files=$(shopt -s nullglob dotglob; s=(MYPATH/*); echo ${s[*]}) 
echo "MYPATH contains $files files"

This will work correctly even if filenames contains spaces.

| improve this answer | |
  • Using an array instead of invoking a subshell will make this even better. This answer does that. – codeforester Mar 6 at 21:17
  • @codeforester, the solution needs to know what are current shell opts. So one would need code to set opts and revert if needed (or figure out opts and count according to them). This will bloat the code and make it less readable. If this part of the code is on a performance critical path, then it might be worth it (or not, needs testing). For a normal use case where you check one directory, I think this answer is safe, short and self contained. If you don't need portability between scripts (which possibly use different shell opts), then the other answer is good. – akostadinov Mar 8 at 10:10
1
if find "${DIR}" -prune ! -empty -exit 1; then
    echo Empty
else
    echo Not Empty
fi

EDIT: I think that this solution works fine with gnu find, after a quick look at the implementation. But this may not work with, for example, netbsd's find. Indeed, that one uses stat(2)'s st_size field. The manual describes it as:

st_size            The size of the file in bytes.  The meaning of the size
                   reported for a directory is file system dependent.
                   Some file systems (e.g. FFS) return the total size used
                   for the directory metadata, possibly including free
                   slots; others (notably ZFS) return the number of
                   entries in the directory.  Some may also return other
                   things or always report zero.

A better solution, also simpler, is:

if find "${DIR}" -mindepth 1 -exit 1; then
    echo Empty
else
    echo Not Empty
fi

Also, the -prune in the 1st solution is useless.

EDIT: no -exit for gnu find.. the solution above is good for NetBSD's find. For GNU find, this should work:

if [ -z "`find \"${DIR}\" -mindepth 1 -exec echo notempty \; -quit`" ]; then
    echo Empty
else
    echo Not Empty
fi
| improve this answer | |
1

This solution is using only shell built-ins:

function is_empty() {
  typeset dir="${1:?Directory required as argument}"
  set -- ${dir}/*
  [ "${1}" == "${dir}/*" ];
}

is_empty /tmp/emmpty && echo "empty" || echo "not empty"
| improve this answer | |
0

This is all great stuff - just made it into a script so I can check for empty directories below the current one. The below should be put into a file called 'findempty', placed in the path somewhere so bash can find it and then chmod 755 to run. Can easily be amended to your specific needs I guess.

#!/bin/bash
if [ "$#" == "0" ]; then 
find . -maxdepth 1 -type d -exec findempty "{}"  \;
exit
fi

COUNT=`ls -1A "$*" | wc -l`
if [ "$COUNT" == "0" ]; then 
echo "$* : $COUNT"
fi
| improve this answer | |
0

This work for me, to check & process files in directory ../IN, considering script is in ../Script directory:

FileTotalCount=0

    for file in ../IN/*; do
    FileTotalCount=`expr $FileTotalCount + 1`
done

if test "$file" = "../IN/*"
then

    echo "EXITING: NO files available for processing in ../IN directory. "
    exit

else

  echo "Starting Process: Found ""$FileTotalCount"" files in ../IN directory for processing."

# Rest of the Code
| improve this answer | |
0

I made this approach:

CHECKEMPTYFOLDER=$(test -z "$(ls -A /path/to/dir)"; echo $?)
if [ $CHECKEMPTYFOLDER -eq 0 ]
then
  echo "Empty"
elif [ $CHECKEMPTYFOLDER -eq 1 ]
then
  echo "Not Empty"
else
  echo "Error"
fi
| improve this answer | |
0

The Question was:

if [ ./* == "./*" ]; then
    echo "No new file"
    exit 1
fi

Answer is:

if ls -1qA . | grep -q .
    then ! exit 1
    else : # Dir is empty
fi
| improve this answer | |
-1

For any directory other than the current one, you can check if it's empty by trying to rmdir it, because rmdir is guaranteed to fail for non-empty directories. If rmdir succeeds, and you actually wanted the empty directory to survive the test, just mkdir it again.

Don't use this hack if there are other processes that might become discombobulated by a directory they know about briefly ceasing to exist.

If rmdir won't work for you, and you might be testing directories that could potentially contain large numbers of files, any solution relying on shell globbing could get slow and/or run into command line length limits. Probably better to use find in that case. Fastest find solution I can think of goes like

is_empty() {
    test -z $(find "$1" -mindepth 1 -printf X -quit)
}

This works for the GNU and BSD versions of find but not for the Solaris one, which is missing every single one of those find operators. Love your work, Oracle.

| improve this answer | |
  • Not a good idea. The OP simply wanted to test if the directory was empty or not. – roaima May 2 '18 at 14:05
-3

You can try to remove the directory and wait to an error; rmdir will not delete the directory if it is not empty.

_path="some/path"
if rmdir $_path >/dev/null 2>&1; then
   mkdir $_path        # create it again
   echo "Empty"
else
   echo "Not empty or doesn't exist"
fi
| improve this answer | |
  • 4
    -1 This is the kind of code that backfires. rmdir will fail if I have no permission to remove the directory; or if it's a Btrfs subvolume; or if it belongs to a read-only filesystem. And if rmdir doesn't fail and mkdir runs: what if the already removed directory belonged to another user? what about its (possibly non-standard) permissions? ACL? extended attributes? All lost. – Kamil Maciorowski Apr 8 '18 at 21:37
  • 1
    Well, I'm just learning bash and I thought that it could be a faster way rather than iterate through all the directory, but CPUs are powerful and you are right, not secure. – impxd Apr 9 '18 at 5:21
  • -1. Destroying something to check its status is never a great idea! – codeforester Mar 6 at 21:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.