4

I was curious about "|| true" and wrote the following pair of examples.

Example#1

    #!/usr/bin/env bash
rm some_random_file_that_does_not_exist

echo "End of program"

When executed if produces the following result:

$ ./remove.sh
rm: cannot remove 'some_random_file_that_does_not_exist': No such file or directory
End of program

Example#2

#!/usr/bin/env bash

rm some_random_file_that_does_not_exist || true

echo "End of program"

Which produces the following result when executed:

$ ./remove.sh
rm: cannot remove 'some_random_file_that_does_not_exist': No such file or directory
End of program

The only difference I can tell is that in Example#1 the result code of the line that tries to remove the non-existent file is 1 while in Example#2 the result code is 0 (zero).

The way I understand this "|| true" is to ensure that the execution of the command(s) at the left of the "||" operator ends up with result code zero.

So my question is... Is there any other reason apart from this one that justifies the use of "|| true" at the end of a command in Bash?

muru
  • 72,889

1 Answers1

12

|| true may be used to suppress immediate exit on error when the errexit shell option is set; that option is enabled with set -e, either by set -e explicitly in the script, or by invoking the script with an explicit interpreter and options: bash -e scriptname. In sh-like shells like bash, : (a utility that does nothing, successfully) may also be used in place of true, like || :.

It may also be used in Makefile recipes with the same purpose.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
dimich
  • 416
  • 1
    ||: should work in any POSIX shell, both the || operator and the : command are standard. (And whatever the minor differences between : and true were, they're not relevant here.) Though I'd rather write || true than ||:, as especially without the space in between, the latter seems unnecessarily obfuscated. – ilkkachu Sep 08 '22 at 05:15
  • 2
    Regarding usage in Makefile, GNU make supports - prefix to ignore command failure but i also have seen || true. Maybe it was for portability, i'm not sure about other implementations. – dimich Sep 08 '22 at 05:20
  • @dimich I'm pretty sure I was using that in makefiles long before GNU make was mainstream. I think this was from SysV.3 or BSD era, if not earlier – Chris Davies Sep 08 '22 at 05:50
  • 1
    Stuart Feldman’s original make supported -, I don’t think I’ve ever come across an implementation that didn’t. – Stephen Kitt Sep 08 '22 at 06:28
  • Many programmers don't known make so well, so they may just use what they know (so shell syntax, which works). – Giacomo Catenazzi Sep 08 '22 at 11:59
  • 2
    The - prefix is definitely more idiomatic in makefiles. But you might need to use ||true if you have a multi-line recipe and you need to ignore intermediate errors. – Barmar Sep 08 '22 at 15:01