1

I have following function which checks connection for internet (I know there are better ways to check for internet connection but that's not the topic):

function checkInternet() {
    local HOST="http://google.com"
    local WGET="/usr/bin/wget"
    $WGET -q --tries=10 --timeout=10 --spider $HOST

    if [[ $? -eq 0 ]]
    then
        echo "online"
    else
        echo "offline"
    fi
}

Now I want to request the return value of the function directly in an if-statement:

I tried several scripts similar to e.g. this one (what I found here):

if( $(checkInternet) -eq "online" )
then
    echo "Function returned online"
else
    echo "Function returned offline"
fi

I don't want to initialisize further variables before the if-statement what I meant with "directly".

Community
  • 1
  • 1
h0ch5tr4355
  • 2,092
  • 4
  • 28
  • 51

3 Answers3

2

You can use this in BASH to check the output of a function:

[[ $(checkInternet) == online ]] && echo "Function returned online" || 
        echo "Function returned offline"

To compare conditions use [[...]] (preferable) or [...].

You can simplify above to to just this without evaluating any conditions:

echo "Function returned $(checkInternet)"
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

A case statement will do this nicely and without non-portable bashisms:

case $(checkInternet) in
  (online)  echo is online;;
  (offline) echo is offline;;
esac

You can also make your checkInternet return a status, which simplifies things in an if:

...
if [ $? -eq 0 ]; then
    true
else
    false
fi

Along with

if checkInternet; then
   # online
else
   # offLine
fi
Jens
  • 69,818
  • 15
  • 125
  • 179
  • 1
    Thank you, also a nice solution, but I've taken anubhava's solutions already – h0ch5tr4355 Nov 13 '15 at 13:42
  • @h0ch5tr4355 You shouldn't. It's clearly inferior, since it uses bashisms. You will never regret a portable POSIX shell solution. There will come a day when you find yourself on a non-Linux box. Be wise, learn proper shell programming from the beginning and don't be trapped by **all the world's a bash**. – Jens Nov 13 '15 at 13:50
  • @h0ch5tr4355, don't forget to accept it then: http://stackoverflow.com/help/someone-answers – glenn jackman Nov 13 '15 at 13:51
  • @Jens, if you want to return based on wget's exit status, just leave it as the last line of the function (since $? -eq 0 is already "success") – glenn jackman Nov 13 '15 at 13:53
1

You are not actually returning a value from your checkInternet () function. If you look at the example you posted, you'll see that their function has a return statement at the end.

EkcenierK
  • 1,429
  • 1
  • 19
  • 34