0

Can't seem to get this to evaluate to true

is_equal () {
  in="$1"
  if [[ "$in" == "385" ]]; then
    return 0
  else
    return 1
  fi
}
a= is_equal 385
if [[ "$a" ]]; then
  echo "equal"
else
  echo "NOT equal"
fi

$ ./equal_nums.sh 
NOT equal
$
7
  • 1
    Try a=$(is_equal 385) But as for me better use if is_equal 365 ; then ... Commented Jan 23, 2015 at 19:20
  • Spaces! Why all the spaces? Also $( is_equal ..). Commented Jan 23, 2015 at 19:20
  • ==is a string or pattern comparison; -eq is for integers... Commented Jan 23, 2015 at 19:31
  • The function can be simplified also. It is useless operate if test ... return ... so the function can be is_equal() { [[ "$1" -eq "385" ]] } Commented Jan 23, 2015 at 19:36
  • @Costas I tried both your good suggestions but I still get NOT equal. Commented Jan 23, 2015 at 19:51

1 Answer 1

5

Your function has an exit status but no output. Your variable $a will always be empty, so the [[ $a ]] test will always be "false"

You truly want this:

if is_equal 42; then ...

But what you think you want is this

is_equal 42                # don't capture the output
a=$?                       # but do grab the exit status
if [[ $a -eq 0 ]]; then ...

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.