0

I want my bash scripts to detect execution errors and exit.

For the longest time I've been using the try/yell/die approach as seen here.

yell() { echo "$0: $*" >&2; }
die() { echo -e "\e[31m$*\e[0m"; exit 1; }
try() { "$@" || die "cannot $*"; }

However this requires me to wrap my commands line this;

try curl https://blah.com | try bash

It seems the better approach would be to use;

set -e
set -o pipefail
set -E

Are there any downsides to using the set approach, opposed to try/yell/die?

Community
  • 1
  • 1
SleepyCal
  • 5,739
  • 5
  • 33
  • 47

2 Answers2

1

See Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected? for some related discussion. – Tom Fenech

Community
  • 1
  • 1
Armali
  • 18,255
  • 14
  • 57
  • 171
1

FYI:

I use ...

#!/usr/bin/env bash

shout() { echo "$0: $*" >&2; }
die() { shout "${@:2} ($1)"; exit $1; }
try() { "$@" || die $? "cannot $*"; }

2 minor differences:

  1. The exit code we eventually receive is the one that was generated by the command being tried.
  2. The shout includes the exit code after the command in (, ).
Richard A Quadling
  • 3,769
  • 30
  • 40