Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


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

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

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

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

Not quite sure what you're asking, but:

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

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" ;;
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

Your Answer


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.