Test if a directory is empty in Bash

By | May 25, 2016

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>)" ]
echo "<path> is empty!"
echo "<path> is not empty"

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.