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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user121196
  • 30,032
  • 57
  • 148
  • 198
  • Possible duplicate of [bash functions: return boolean to be used in if](http://stackoverflow.com/questions/5431909/bash-functions-return-boolean-to-be-used-in-if) – Mad Physicist Feb 01 '16 at 19:09

3 Answers3

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.

Michael Day
  • 1,007
  • 8
  • 13
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.

that other guy
  • 116,971
  • 11
  • 170
  • 194
0

you can check if a directory is empty by:

[ "$(ls -A /path/to/directory)" ] && echo "Not Empty" || echo "Empty"
Hamid Reza Moradi
  • 429
  • 2
  • 4
  • 11