1

I would like to use the return value of a bash function in a 'if not' statement. The following is an example script:

#!/bin/bash

function myfunction () {
 if [ $1 = "one" ]; then
  return 1
 elif [ $1 = "two" ]; then
  return 2
 else
  return 0
 fi
}

if myfunction "two"; then
 # just using echo as an example here
 echo yep $?
else
 # just using echo as an example here
 echo nope $?
fi

Is there a way to modify the part 'if myfunction "two"' in a way that this script echoes 'yep 2'? I can only figure out this ugly way. How can can I solve this a better way?

4 Answers 4

2

if myfunction "two" in pseudocode is if the myfunction return code is zero when run with a single argument "two". If you want to reverse the comparison (is not zero) you can simply add a ! between if and myfunction.

5
  • That works great - except that $? is changed as well. But thats how the system works I guess... Commented Jun 6, 2013 at 10:57
  • @Den Yes, $? always holds the result of the last command. You are supposed to save it to some other variable if you want to keep the result of a specific command for later. Commented Jun 6, 2013 at 11:51
  • @Den Note that if ...; then ... can be rewritten as ...; if $? = 0; then ... for elided parts in the same order. That may be more in line with what you want to do, because then you have a good place in which to save the value of $? to somewhere else. Commented Jun 6, 2013 at 11:53
  • Ah, right, silly me. Commented Jun 6, 2013 at 12:00
  • Note that this "reversal" of the exit code involves some information loss: Instead of a value from 0 through 255 you'll get either 0 or 1. Commented Jun 6, 2013 at 12:16
1

Not quite sure what you're asking, but:

myfunction two; (( $? == 2 )) && echo yes || echo no
0
myfunction "two"
myvar=$?
if [ $myvar -gt 0 ]; then
 echo yep $myvar
else
 echo nope $myvar
fi
0

Why not do the echoing from within the function? This should be straightforward:

myfunction() {
    case "$1" in 
        one) echo "nope 0" ;;
        two) echo "yep 2" ;;
    esac
}
myfunction one
myfunction two
1
  • The echoing is only to illustrate the example. The real script is only about the if... Commented Jun 6, 2013 at 10:53

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.