5

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?

2

1 Answer 1

13

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

6
  • 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. Commented Sep 8, 2022 at 5: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. Commented Sep 8, 2022 at 5: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 Commented Sep 8, 2022 at 5:50
  • 1
    Stuart Feldman’s original make supported -, I don’t think I’ve ever come across an implementation that didn’t. Commented Sep 8, 2022 at 6:28
  • 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. Commented Sep 8, 2022 at 15:01

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.