11

I am trying to pass arguments to a function within an if statement and then evaluating what the function returns (in bash). The result I am getting is incorrect. How do you properly do this?

#!/bin/bash

foo() {
    if [ $1 = "zero" ]; then
        echo "0"
    else 
        echo "1"
fi
}

arg="zero"
if foo $arg -eq 0 ; then
    echo "entered 0"
else
    echo "entered something else"
fi

arg="blah"
if foo $arg -eq 0 ; then
    echo "entered 0"
else
    echo "entered something else"
fi

Not the desired results:

cknight@macbook:~/work$ ./test.sh
0
entered 0
1
entered 0

3 Answers 3

10

You can either return a result from your function or use $() to capture its output:

if [ $(foo $arg) -eq 0 ] ; then
Sign up to request clarification or add additional context in comments.

2 Comments

What if I am using multiple functions within the if statement with && or ||? In that case this does not work.
@7heViking Then definitely prefer the return form but instead of capturing the output, examine the returned value. Basically, if foo "$arg"; then (notice also the proper quoting of the argument).
4

Are you sure you need your function to echo 0 or 1? It looks more like you want something like

foo() {
  if [ $1 = "zero" ]; then
    return 0
  else 
    return 1
  fi
}

# Or even just simply foo () { [ $1 = "zero ]; }

arg="zero"
if foo $arg; then
    echo "entered 0"
else
    echo "entered something else"
fi

arg="blah"
if foo $arg; then
    echo "entered 0"
else
    echo "entered something else"
fi

Comments

1

Not sure what you want to do...

Your foo() function always returns with success, use return.

You pass to your foo() function a second and a third parameter -eq 0 but they aren't used. Do you want to check the exit status? That's simply if foo $arg; then ..; fi.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.