0

I have these 2 functions on 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
}

and

    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[@]}"
}

And I call this from another bashscript. But I would like to be able to set a status (or similar) to check if for example "mail" is installed, then "mail"s status should be 1, which I then can use in another check in the script using the function; something like this:

if [mail = 1]; then
do something
else something else
fi
b0red
  • 47
  • 7
  • 1
    `[` is a command. Commands are separated from their arguments with spaces. You can't run `[mail` instead of `[ mail` any more than you can run `lsfoo.txt` instead of `ls foo.txt` – Charles Duffy Aug 31 '18 at 19:14
  • ...and if you're only targeting bash 4.0 or later, `case ${REPLY,,} in` is a lot faster than spinning up a subshell with a pipeline running `tr`. – Charles Duffy Aug 31 '18 at 19:26
  • (There are also a bunch of quoting issues -- consider running your code through http://shellcheck.net/ and fixing what it finds before asking questions here). – Charles Duffy Aug 31 '18 at 19:36

2 Answers2

1

You need the return statement in your function. return 0 means success and return 1 (or any integer between 1 and 255) is an error.

You can test with if:

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

You could:

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

but that can be messed up easily, so the first pattern is better. $? is the exit or return status of the previous command.

cdarke
  • 42,728
  • 8
  • 80
  • 84
0

you could run which mail which should give you the path of the package installed. For example:

which bash /usr/local/bin/bash

so you could check if the return of which bash is 0 or not using $? If it is 0 then the package is installed

Pablo Marti Cordero
  • 944
  • 2
  • 9
  • 23
  • 1
    `which` is relatively expensive, as it's an external command, not part of the shell. `if command -v bash >/dev/null 2>&1; then` is guaranteed to be both present and fast (built-in, not an external executable) on all POSIX-compliant shells. – Charles Duffy Aug 31 '18 at 19:21