2

I want to know how best to exit a script when an error occurs within a sub-command - specifically, in an assignment (i.e., of the form MYVAR="$(...)").

The minimal example of my problem is the following bash script.

#!/bin/bash

set -e

fail() {
  echo "Some error" >&2
  exit 1
}

main() {
  local my_val="$(fail)"

  echo 'Success!'
}

main

This will output the following:

Some error
Success!

What I am trying to figure out is how best to detect and handle the failure which occurs so that the Success stage is never reached.

Toby Sullivan
  • 198
  • 10
  • 2
    (1) Be sure you can successfully complete the exercises in [BashFAQ #105](http://mywiki.wooledge.org/BashFAQ/105) before using `set -e`. (2) Don't specify `local val=$(something)` as one line. `local val` should be one line; `val=$(something)` should be another. – Charles Duffy Apr 11 '18 at 04:05
  • ...by the way, if the BashFAQ #105 exercises don't scare you off from `set -e`, the [differences between how "compatible" shells implement it](https://www.in-ulm.de/~mascheck/various/set-e/) might. – Charles Duffy Apr 11 '18 at 04:07
  • `main() { local my_val; my_val=$(fail) || return; echo 'Success!'; }` is how I would write that. Yes, explicitly checking exit status where appropriate to do so -- just as someone is obliged to do in C, or Go, or the multitude of other languages that (like bash!) don't support exceptions. – Charles Duffy Apr 11 '18 at 04:10

0 Answers0