fifty arashi fifty arashi - 19 days ago 6
Bash Question

How to check if folder is empty or have folder file use shell-script?

i have a question

i try some function like


DIR=/path/tmp/

if [ -d "$DIR" ]; then


and


if [ -f "$DIR" ]; then


but only check /path/tmp this path

how can i do?

Answer

You can use ls -A for this:

if [ "$(ls -A $DIR 2> /dev/null)" == "" ]; then
    # The directory is empty
fi

-A shows all hidden files and directories except the . and .. that are always there, so it will be blank in an empty directory and non-blank in a directory with any files or subdirectories.

The 2> /dev/null throws away any error messages ls may print (note that checking a non-existant directory will yield a false positive, but you said you already checked that it existed). Checking a directory where you do not have read access also yields a false positive.