在 bash 脚本中使用 if 和布尔函数:当函数返回 true 时,如果条件计算为 false

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14698783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:27:31  来源:igfitidea点击:

using if and a boolean function in bash script: if condition evaluates to false when function returns true

bashfunction

提问by user121196

is_dir_empty(){

    for file in ""
    do
        if [ "$file" != "" ]; 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?

所以 is_dir_empty 返回 1 但如果条件以某种方式评估为 false .... 为什么?

回答by Michael Day

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.

因为 shell 脚本遵循 Unix 约定,期望实用程序在成功时返回零,失败时返回非零,所以布尔条件被反转。

回答by that other guy

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

Glob 没有用双引号展开,因此您总是与文字 value 进行比较/home/tmp/*.sh$1在 for 循环中取消引用,它将 word split 和 glob 扩展为 .sh 文件列表(此在线工具会自动指出这一点)。

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

此外,与 C 不同,零被认为是成功和非零失败。

回答by Hamid Reza Moradi

you can check if a directory is empty by:

您可以通过以下方式检查目录是否为空:

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