6
is_dir_empty(){

    for file in "$1"
    do
        if [ "$file" != "$1" ]; then
            return 0
        fi
    done
    echo "return 1"
    return 1
}

file="/home/tmp/*.sh"

if is_dir_empty "$file"; then
    echo "empty"
else echo "not empty"
fi

it outputs

return 1
not empty

so is_dir_empty returned 1 but if condition evaluated to false somehow.... why?

1

3 Answers 3

9

Because shell scripts follow the Unix convention of expecting utilities to return zero for success and non-zero for failure, so boolean conditions are inverted.

Sign up to request clarification or add additional context in comments.

Comments

2

Globs are not expanded in double quotes, so you're always comparing against the literal value /home/tmp/*.sh. Unquote $1 in the for loop, and it'll word split and glob expand into a list of .sh files (this online tool would have pointed this out automatically).

Also, unlike in C, zero is considered success and non-zero failure.

2 Comments

The online tool looks like it would have been useful, is there an equivalent that is up today?
@StuartAxon Today there's ShellCheck. It has an online version and can also be installed locally
0

you can check if a directory is empty by:

[ "$(ls -A /path/to/directory)" ] && echo "Not Empty" || echo "Empty"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.