1

I have a bash script used to make my project. I have set -e in top of the script to break the execution when any component fails.

One of the commands would fail, but it is natural for it to fail. I would like the script to behave as such:

  • Run the script.
  • Reach and run the problematic command.
  • If it fails, don't break execution. Do this ONLY for this command.
Mat
  • 202,337
  • 40
  • 393
  • 406
solidak
  • 5,033
  • 3
  • 31
  • 33

2 Answers2

6

I suggest:

set +e
# your command which would fail
set -e

or

your_command_which_would_fail || true
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Your first proposal would mean to switch `set -e` on after this command *even if it wasn't on before it* (i. e. in another context, after a patch, whatever). – Alfe Jan 03 '18 at 14:15
  • @Alfe: This is also possible with -e and +e: https://stackoverflow.com/a/48019999/3776858 – Cyrus Jan 03 '18 at 14:19
  • Yes, with more code. So I would not propose it for this usecase. – Alfe Jan 03 '18 at 14:22
  • Wow, thanks both @Alfe and @Cyrus for the prompt reply. I went with the `|| true` option. – solidak Jan 03 '18 at 15:01
2

The flag set -e has a bunch of exemptions where it doesn't lead to an abort right away after an executed command failed (exitcode ≠ 0). Among these are the connections as @cyrus proposed (a || b and similar). See man bash for details; it's kind of hard to find, maybe this helps:

man bash | grep -B 20 -A 10000 'Exit.*immediately' | less

My proposal would be to put it in an if:

if command
then
    : "worked nicely"
else
    : "failed, but we don't want to abort"
fi

or @Cyrus's short version:

command || true  # do not abort in case of 'set -e'
Alfe
  • 56,346
  • 20
  • 107
  • 159