0

Within a bash script, how can one signal to the (bash-script-calling human) user that a premature-exit error was triggered, with some sort of custom message?

I want to send an unmistakable failure message like

! ** !

Oops, something went wrong.
This script did NOT successfully finish.

! ** !

so that the user understands the script did not finish successfully. (Sometimes this point is not clear and the user mistakenly assumes the script finished successfully.)

Johnny Utahh
  • 2,389
  • 3
  • 25
  • 41

2 Answers2

3

You should use this instead of set -e:

#!/usr/bin/env bash

trap 'cat<<EOF >&2
! ** !

Oops, something went wrong.
This script did NOT successfully finish.

! ** !
EOF
    exit 1' ERR

[...] # code
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
3

Answering my comment, here is with expanding on (Gilles Quenot's answer) how to preserve the error return code when exiting the script:

#!/usr/bin/env bash

trap 'rc=$?; cat<<EOF >&2
! ** !

Oops, something went wrong.
This script did NOT successfully finish.

! ** !
EOF
    exit $rc' ERR

failme ()
{
  return $1
}

failme 10
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
  • 1
    Just a verbatim copy of my answer + a 'feature' not asked by OP – Gilles Quénot Jun 22 '20 at 01:12
  • 1
    I (the OP) consider this a critical feature, even though it was certainly not explicitly requested. I consider passing through the return code for command failures to be essential for tiered script calling. Many thanks Léa. – Johnny Utahh Jun 22 '20 at 01:15