Home > database >  Interpret return value of bash function
Interpret return value of bash function

Time:12-07

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

CodePudding user response:

Perhaps you want

#!/bin/bash

a() {
   return 1
}

echo "test1"
if ! a; then
  echo "test2"
fi

Or for short

echo "test1"
a || echo "test2"

CodePudding user response:

It seems that set -e can do what you want :

#!/usr/bin/env bash

set -e

function a {
   return 1
}

echo "test1"
a
echo "test2"

set -e might be a "bad idea" : https://mywiki.wooledge.org/BashFAQ/105#Exercises

  • Related