Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

4 Answers 4

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.

share|improve this answer
    
That works great - except that $? is changed as well. But thats how the system works I guess... –  Den Jun 6 '13 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. –  Michael Kjörling Jun 6 '13 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. –  Michael Kjörling Jun 6 '13 at 11:53
    
Ah, right, silly me. –  Michael Kjörling Jun 6 '13 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. –  l0b0 Jun 6 '13 at 12:16
add comment

Not quite sure what you're asking, but:

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

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
share|improve this answer
    
The echoing is only to illustrate the example. The real script is only about the if... –  Den Jun 6 '13 at 10:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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