Johnny Utahh
Johnny Utahh

Reputation: 2478

In a bash script: how to signal to the (human) user that an error triggered a premature exit?

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.)

Upvotes: 0

Views: 56

Answers (2)

Léa Gris
Léa Gris

Reputation: 19545

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

Upvotes: 3

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185025

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

Upvotes: 3

Related Questions