1

I think my question is similar to this one but with one extrat step - say I have 3 scripts:

  1. main_script.sh
  2. report_success.sh
  3. report_failure.sh

How can I do something like this pseudo-code does:

if (main_script.sh finished without error):
run report_success.sh
else:
run report_failure.sh

?

Thanks!

user3768495
  • 219
  • 2
  • 8

3 Answers3

5
if main_script.sh; then
    report_success.sh
else
    report_failure.sh
fi

This uses the exit status of main_script.sh to determine whether it was successful (exit status 0) or not (exit status non-zero) and then runs the appropriate report script.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
dhanlin
  • 61
  • 5
2

Assuming your main_script.sh is fairly standard and passes a 0 for a successful run and 1 for an unsuccessful run, you can probe the status via $? like so:

./main_script.sh
if [ $? -eq 0 ]; then
    ./report_success.sh
else
    ./report_failure.sh
fi
Jason K Lai
  • 534
  • 2
  • 8
  • There is almost never a reason to compare or even use `$?` directly, unless you need to save it for later (which you don't need to here). – Kusalananda Aug 20 '19 at 21:15
2

It's as simple as this:

true && echo ok || echo fail

false && echo ok || echo fail

A typical command may return null (as true does) or may return not null (as false does) depending on whether the operation succeeded or failed.

./main_script.sh && ./report_success.sh || ./report_failure.sh

If you had to run several commands for the ok or fail case, use braces. No need for several scripts:

./main_script.sh && { echo ok ; echo ok2 } || { echo fail ; echo fail2 ; }

Janka
  • 446
  • 3
  • 5
  • Note that your commands with `&&` and `||` would run `./report_failure.sh` if _either_ of `./main_script.sh` or `./report_success.sh` failed. This is not the same thing as an explicit `if-then-else`. – Kusalananda Aug 20 '19 at 21:14
  • Well, yes. But failure of the success report is a failure, too. – Janka Aug 20 '19 at 21:33