Help Needed regarding a shell script (IF nested loop)

Hello Gurus,
I am trying to develop a simple shell script where there are 3 steps.
Step1 should run by default when a function is called. If the out of step 1 is a success(planning to use exit 0 option) , it should proceed with step2, else exit.
When at step2, if the output is a success(planning to use exit 0 option), it should proceed to step 3 or else exit.
Finally when step 3 runs, if it is successful (planning to use exit 0 option) that should be the end of it, else provide the error details.

I cannot visualize how to use “IF CONDITION” or NESTED IF condition.

Also what should be my approach, if there were say 10 or 15 steps, NESTED IF’s would be so complex.

Your help and comments are highly appreciated.

Thanks & Regards,
Prem

Hi @premjitger

I can’t quite visualize what you’re saying here. One thing though is that you can’t use exit to provide a return value from a function; that will cause the script to stop entirely and return to the command prompt.

There is no concept of function return values in shell.
You can use echo to simulate a return value and probably do something like this, however you can’t print anything from inside the functions other than the return value.

func_that_succeeds() {
    # do stuff
   echo 0
}

func_that_fails() {
   #do stuff
  echo 1
}

if [ "$(func_that_succeeds)" != "0" ]
then 
     # maybe print something
     exit 1
fi 

if [ "$(func_that_fails)" != "0" ]
then
    exit 1
fi 

Or you can short-hand the if’s if you just want to exit the script immediately

[ "$(func_that_succeeds)" == "0" ] || exit 1
[ "$(func_that_fails)" == "0" ] || exit 1

which reads kind of like
function_that_succeeds equals zero or exit 1 (if it doesn’t)

With either you don’t need to nest the if’s

Alternatively, use some global script variable. The first function that sets the variable to anything other than zero will cause the script to exit.

retval=0

func_that_succeeds() {
    # do stuff
}

func_that_fails() {
   #do stuff
  if [ some_error_condition ]
  then
     retval = 1
  fi
}

func_that_succeeds
[ "$retval" == "0" ] || exit 1
func_that_fails
[ "$retval" == "0" ] || exit 1

Thank you Alistair for your response. I will try to put my problem statement more clearly next time.