true
is portable, but doesn't by itself return. return true
is not portable, and also doesn't work reliably.
If you have a function like so:
f() {
true
}
Then yes, it will portably return from the function with an exit status of zero. When falling off from the end, the exit status of the last command is returned as the exit status of the function.
But of course this doesn't return with a truthy status, as the true
in the middle by itself doesn't affect the control flow.
g() {
# silly example condition
if [ 1 = 1 ]; then
true
fi
echo something else
false
}
But you could add an explicit return, as return
without arguments also uses the exit status of the last command:
The value of the special parameter '?' shall be set to n, an unsigned decimal integer, or to the exit status of the last command executed if n is not specified. If n is not an unsigned decimal integer, or is greater than 255, the results are unspecified.
h() {
# silly example condition
if [ 1 = 1 ]; then
true
return
fi
echo something else
false
}
Now, if you were to try return true
, it might appear it'd do what you wanted in some shells, but in the end it probably doesn't. At least in zsh, it appears to take the argument as an arithmetic expression, so return true
would use the value of the variable true
, or zero by default if it's not set.
% i() { return 1+1; }
% i; echo $?
2
% unset true
% j() { return true; }
% j; echo $?
0
% true=123
% j; echo $?
123
If you can arrange for true
to be always set to 0
, and false
to be set to 1
, and trust the users of your script library to not mess with those, then you could use return true
and return false
in zsh, or return "$true"
and return "$false"
in a standard shell. I wouldn't recommend that with those names but maybe something like true_return_value
or false_return_value
could be used.
Otherwise, you could use true; return
and false; return
in a standard shell, but I'm not sure if that's any more readable than return 0
and return 1
. The fact that the truthy return value is zero should be familiar to shell programmers in any case.
true
andfalse
are external commands (that do indeed exit with 0 and 1 respectively). Do you really want to fork off a new process just for some minor advantage in readability?true
andfalse
are builtin in most shells, these days. egbash-5.1$ type true true is a shell builtin