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
  • 34,719
  • 24
  • 185
  • 251
user121196
  • 28,674
  • 57
  • 144
  • 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
  • 937
  • 6
  • 12
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
  • 109,738
  • 11
  • 156
  • 185
0

you can check if a directory is empty by:

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