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
$
  • 1
    Try a=$(is_equal 385) But as for me better use if is_equal 365 ; then ... – Costas Jan 23 '15 at 19:20
  • Spaces! Why all the spaces? Also $( is_equal ..). – muru Jan 23 '15 at 19:20
  • ==is a string or pattern comparison; -eq is for integers... – jasonwryan Jan 23 '15 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" ]] } – Costas Jan 23 '15 at 19:36
  • @Costas I tried both your good suggestions but I still get NOT equal. – Michael Durrant Jan 23 '15 at 19:51
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 ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.