Function - Make your function return an exit status

Hi All,

Good Day, seeking for your assistance on how to not perform my 2nd, 3rd,4th etc.. function if my 1st function is in else condition.

#Body

function1() 
{
if [ - e test.xt] 
then
echo "exist" 
else
echo "not exist" 
} 

#if not exist in function1 my all other function will not proceed. 

function2() 
{
cat test.txt
} 

#Main
function1
function2
etc.. 

if i put my function1 and function2 in main it always proceed on function 2 even though theres an error in function1. im not sure how to start.

TIA

  1. Make your function return an exit status.
  2. Act on the exit status.
if [ - e test.xt ] 
then
  echo "exist"
  return 0
else
  echo "not exist"
  return 1
fi

For practical reason in the shell the exit status 0 means ok/true.

if function1
then
  function2
fi
function1 &&
  function2

The logical AND needs to evaluate(run) the RHS only if the LHS was true.

1 Like

oww.. i can also put the function inside if?

--- Post updated at 12:39 PM ---

where should i put the condition of function? in last?

Yes, a function behaves like a command.

if command1; then command2; fi

If command1 was successful (exit 0) then run command2.
The same can be achieved with the logical AND:

command1 && command2

For that matter, there's already return values here you aren't checking.

function2() 
{
        cat test.txt # If this fails, $? will be nonzero
} 

if ! function2
then
        echo "Could not execute function2" >&2
        exit 1
fi

Just be careful not to alter the value of $? by doing anything else, or set it to what you want with the 'return' statement.

1 Like