fifty arashi fifty arashi - 6 months ago 30
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


if [ -d "$DIR" ]; then


if [ -f "$DIR" ]; then

but only check /path/tmp this path

how can i do?


You can use ls -A for this:

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

-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.