试图在bash功能中设置状态

时间:2018-08-31 19:02:12

标签: bash

我在bash上有这两个功能;

function ask_yes_or_no() {
    read -p "$1 ([y]es or [N]o): "
    case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
        y|yes) echo "yes" ;;
        *)     echo "no" ;;
    esac
}

    function is_it_installed()
{
    i=0; n=0; progs=($@);
    for p in "${progs[@]}"; do
        if hash "$p" &>/dev/null
        then
            echo "$p is installed"
            let c++
        else
            echo "'$p' is not installed. Do you want to install '$p'"
            if [[ "yes" == $(ask_yes_or_no "Are you sure?") ]]
            then
                apt-get install $p
            else
                echo="Skipped installation of: '$p'"
                # exit 1
            fi
            let n++
        fi
    done
    printf "%d of %d programs were installed.\n"  "$i" "${#progs[@]}" 
    printf "%d of %d programs were missing\n" "$n" "${#progs[@]}"
}

我从另一个bashscript来称呼它。但是我希望能够设置一个状态(或类似的状态)来检查是否已安装“ mail”,那么“ mail”的状态应为1,然后我可以使用该函数在脚本中进行其他检查;像这样的东西:

if [mail = 1]; then
do something
else something else
fi

2 个答案:

答案 0 :(得分:1)

您需要在函数中使用return语句。 return 0表示成功,而return 1(或1到255之间的任何整数)是错误。

您可以使用if进行测试:

if func_name
then
    # func_name was successful
else
    # func_name was unsuccessful
    echo $?     # actual returned number
fi

您可以:

func_name
if (( $? == 1 ))
then
    ...
fi

但是这很容易弄乱,所以第一种模式更好。 $?是上一条命令的退出或返回状态。

答案 1 :(得分:0)

您可以运行which mail,它应该为您提供安装软件包的路径。例如:

which bash /usr/local/bin/bash

因此您可以使用which bash检查$?的返回值是否为0,或者如果返回值为0,则说明软件包已安装