Test if a directory is empty in Bash

Posted: 29th January 2015 by Tim in Bash, Linux
Tags: , , , , , ,

Using Bash, there are a number of ways to test if a directory is empty. One of those ways is to use ls -A to list all files, including those starting with . and see if anything is printed. This can be done like so:

if [ ! "$(ls -A <path>)" ]
then
    echo "<path> is empty!"
else
    echo "<path> is not empty"
fi

Or inline:

if [ ! "$(ls -A <path>)" ]; then echo "empty!"; fi

Or, for a slightly less readable version:

test "$(ls -A <path>)" || echo "empty!"

This works because test "" is true, and any other string value is false. If the directory is empty, ls -A will return an empty string.

  1. lapin says:

    if [ ! “$(ls -A “$DIR”)” ]; then echo “empty!”; fi