Search code examples
bashreturnexit-code

Interpret return value of bash function


I would like to interpret the return value of the function a in the parent bash.
I want to use return to stop an intermediate script in the parent bash.
In this case it means, that test2 shouldn't be executed. But it doesn't work.
And I don't want to use exit, because it stops "everything" in the parent process.

Does exist a solution to do that?

Script:

#!/bin/bash

function a {
   return 1
}

echo "test1"
a
echo "test2"

Output:

test1
test2

The output should be just

test1

Solution

  • Perhaps you want

    #!/bin/bash
    
    a() {
       return 1
    }
    
    echo "test1"
    if ! a; then
      echo "test2"
    fi
    

    Or for short

    echo "test1"
    a || echo "test2"