≡ Menu

How to check if a directory is empty in a shell script?

Question – I need to check if a directory is empty in a bash shell script. Is there a Linux command that I can use to do this?

The following code with check if a directory is empty in a bash shell script:

#!/bin/bash
DIRECTORY="/root/"
if [ "$(ls -A $DIRECTORY)" ]; then
   echo "$DIRECTORY is not empty!"
else
   echo "$DIRECTORY is empty!"
fi

The above code will check if the directory /root is empty. If the directory does not exist, it will still print the string Empty.

The ls -A command will print out all files in a directory except the special directories “.” and “..”.

Comments on this entry are closed.