true
was not built into the Bourne shell. :
always was (it was the way to enter comments before #
was introduced).
That, and because it's shorter to type is probably the main reason people prefer :
over true
.
Note another difference in POSIX shells (for bash
, only in POSIX mode): while true
is a regular builtin (doesn't even have to be builtin), :
is a special builtin. That has a few implications, most of which are unlikely to have any impact in this particular case:
If a :
command fails, including because of a failed redirection, that causes the shell to exit. In practice, that probably won't make a difference unless you pass redirections to :
$ sh -c ': > / ; echo HERE'
sh: 1: cannot create /: Is a directory
$ sh -c 'true > /; echo HERE'
sh: 1: cannot create /: Is a directory
HERE
in var=value :
, var
remains set to value
after :
returns, not in the case of true
:
$ var=1; var=2 : ; echo "$var"
2
$ var=1; var=2 true; echo "$var"
1
Also note that || true
works in shells of the rc
and csh
families but not || :
(but not to cancel set -e
in csh
).
|| :
is not the same as :
. It means or run :
otherwise (that is, if the preceding pipeline fails).
set -e
false
Would cause the shell to exit because of set -e
(aka the errexit
option) and false
has a non-zero (failure) exit status. The set -e
effect is cancelled if the command that returns a non-zero exit status is used as a condition like in:
if false; then ...
while false; do ...
false && : ...
false || : ...
false && :
only cancels set -e
. false || :
cancels the effect of set -e
and sets the exit status to 0
so is more idiomatic to say that we want to ignore a failure exit code of the command. Most would argue that || true
is more legible (conveys the intention more clearly).
||:
(with no space) is also valid in bash. It does the same thing as|| :
or|| true
. – Bruno Bronosky Jan 22 '17 at 04:53