我想写一个bash函数,检查文件是否具有某些属性并返回true或false。然后我可以在我的脚本中的“如果”中使用它。但是我应该返回什么呢?

function myfun(){ ... return 0; else return 1; fi;}

然后我这样使用它:

if myfun filename.txt; then ...

当然这行不通。如何才能做到这一点呢?


当前回答

在返回之前立即使用true或false命令,然后不带参数返回。返回值将自动使用上一个命令的值。

如果不使用1或0,则为return提供参数是不一致的、特定于类型的并且容易出错。正如前面的注释所述,在这里使用1或0不是处理这个函数的正确方法。

#!/bin/bash

function test_for_cat {
    if [ "$1" = "cat" ];
    then
        true
        return
    else
        false
        return
    fi
}

for i in cat hat;
do
    echo "${i}:"
    if test_for_cat "${i}";
    then
        echo "- True"
    else
        echo "- False"
    fi
done

输出:

$ bash bash_return.sh

cat:
- True
hat:
- False

其他回答

在返回之前立即使用true或false命令,然后不带参数返回。返回值将自动使用上一个命令的值。

如果不使用1或0,则为return提供参数是不一致的、特定于类型的并且容易出错。正如前面的注释所述,在这里使用1或0不是处理这个函数的正确方法。

#!/bin/bash

function test_for_cat {
    if [ "$1" = "cat" ];
    then
        true
        return
    else
        false
        return
    fi
}

for i in cat hat;
do
    echo "${i}:"
    if test_for_cat "${i}";
    then
        echo "- True"
    else
        echo "- False"
    fi
done

输出:

$ bash bash_return.sh

cat:
- True
hat:
- False

在只使用选项-d检查目录时要小心! 如果变量$1为空,检查仍然会成功。当然,还要检查变量是否为空。

#! /bin/bash

is_directory(){

    if [[ -d $1 ]] && [[ -n $1 ]] ; then
        return 0
    else
        return 1
    fi

}


#Test
if is_directory $1 ; then
    echo "Directory exist"
else
    echo "Directory does not exist!" 
fi
myfun(){
    [ -d "$1" ]
}
if myfun "path"; then
    echo yes
fi
# or
myfun "path" && echo yes

重写一下可能有用 函数myfun(){…返回0;否则返回1;Fi;}作为这个函数myfun(){…返回;其他假;fi;}。也就是说,如果函数中的最后一条指令为false,则整个函数的结果为false,但无论如何都会返回结果为true的中断函数。我相信至少对我的bash解释器来说是这样的。

出于代码可读性的考虑,我认为返回true/false应该:

在一条线上 成为一个命令 容易记住 提到关键字return后跟另一个关键字(真或假)

我的解决方案是返回$(true)或返回$(false)如下所示:

is_directory()
{
    if [ -d "${1}" ]; then
        return $(true)
    else
        return $(false)
    fi
}