In many scripts I've inherited from a former employee I keep seeing this pattern:
if (true $SOME_VAR)&>/dev/null; then ... fi
or this one
(true $SOME_VAR)&>/dev/null || SOME_VAR="..."
The man page for true
says it always returns true, hence I keep wondering, what is the point of these checks? In the first case the then
part is always executed, in the second case the right hand part is never executed.
The true and false commands Wherever you see true or false in Bash, it's either a string or a command/builtin which is only used for its exit code. where the command is true . The condition is true whenever the command returns exit code 0.
There are no Booleans in Bash. However, we can define the shell variable having value as 0 (“ False “) or 1 (“ True “) as per our needs.
On Unix-like operating systems, the true command's sole purpose is to return a successful exit status. It is useful when you want part of a command or conditional expression always to be true.
Using true and false As you can see, true simply returns a 0 and false simply returns a 1. Probably the most common use of the true command is to start an infinite loop. Instead of starting a loop with a command like while [ $num -le 12345678 ], you can use while true and the loop continues until you stop it will a ^c.
If set -u
(a.k.a. set -o nounset
) is in effect, true $SOME_VAR
will fail when $SOME_VAR
is not defined. This is therefore a way to test whether the variable is defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With