Bash函数没有正确返回值

时间:2014-09-23 23:52:30

标签: shell unix scripting

我不知道我的功能有什么问题;它没有正确返回值。

function validate_directory_isempty     {
    retval=""

    NumOfFiles=`ls -l $input | egrep -c "^-"`

    if [ "$NumOfFiles" == "0" ];then
            retval=true

    else
            retval=false

    fi
    echo $retval
}


retval=$(validate_directory_isempty /opt/InstallationManager)
echo "retval : " $retval
if [ "$retval" == "true" ]; then
        echo ""
        echo "Installing Installation Manager"

#       Install_IM

else
        echo ""
        echo "DIRECTORY is not empty. Please make sure install location $DIRECTORY is empty before installing PRODUCT"

fi

2 个答案:

答案 0 :(得分:0)

让函数返回true或false的惯用方法是使用return关键字。返回值0表示成功,非零值表示失败。另请注意,如果return不存在,函数将返回执行的最后一个命令的状态。

我会写这样的函数

is_dir_empty() {
    shopt -s nullglob
    local -a files=( "$1"/* )
    (( ${#files[@]} == 0 ))
}

directory=/opt/InstallManager
if is_dir_empty "$directory"; then
    echo "$directory" is empty
fi

第一行设置一个shell选项,模式匹配没有文件扩展为null而不是模式本身作为字符串。

第二行用给定目录中的文件名填充数组。

最后一行测试数组中的元素数量。如果为零条目,则返回成功,否则返回失败。

答案 1 :(得分:0)

我刚刚更换了我的脚本,如下所示

删除了以下命令 retval = $(validate_directory_isempty / opt / InstallationManager) echo" retval:" $ RETVAL

加入 输入= /选择/ InstallationManager validate_directory_isempty

并且有效。

再次感谢您的宝贵意见