1

In a shell script, this is cumbersome:

#!/bin/sh -e
# [...]
set +e
command-that-is-allowed-to-fail
set -e
# [...]

It looks prone to error, too.

Is there not a better way to do this?

(Incidentally, the answer appears in a comment to a partially related question. However, the question and answer have not yet appeared on StackOverflow, as a proper question and answer, as far as I know.)

Community
  • 1
  • 1
thb
  • 13,796
  • 3
  • 40
  • 68
  • Thanks for discovering the duplication. I had been unable to find it. My question is not *exactly* the same, as it turns out, because the other question specifically regards Bash. However, it is close enough to the same to close it. – thb Aug 21 '16 at 11:22

1 Answers1

4

Yes, there is a better way—or, at any rate, there is a more idiomatic, terser, less error-prone way.

#!/bin/sh -e
# [...]
command-that-is-allowed-to-fail || true
# [...]

See how that works? If command-that-is-allowed-to-fail fails, the || operator passes control to the true builtin. The latter does nothing except this: it never fails.

Incidentally, there exists a false command as well, which does nothing except this: it always fails. However, in some shells (like Dash) false is not a builtin, so you might in some circumstances have to invoke it as /bin/false or the like.

NOTE

A mentor taught me this technique about 2004. I doubt that I would have discovered the technique on my own, for it was nonobvious to me. The technique is simple and appealing, though, once one has become acquainted with it. Since learning the technique, I have used it extensively. You can, too.

thb
  • 13,796
  • 3
  • 40
  • 68
  • 1
    I do `|| :`. `true` is too long a word to type out. – Petr Skocik Aug 21 '16 at 10:15
  • @PSkocik: How about that? Apparently, `|| :` even works in Dash. So, in 2016, 12 years later, I can still learn something new, thanks to you. If you choose to make your comment an *answer,* I'd like to upvote it. – thb Aug 21 '16 at 10:19
  • 1
    Thanks, but I don't care that much for points. `true` and `:` are entirely synonymous, AFAIK, except that `:` doesn't have a corresponding executable on my system. – Petr Skocik Aug 21 '16 at 10:23
  • 1
    `:` is POSIX too http://pubs.opengroup.org/onlinepubs/009695399/utilities/colon.html – Petr Skocik Aug 21 '16 at 10:29