Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: usage of `true`

Tags:

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.

like image 913
Eli Korvigo Avatar asked Mar 27 '17 12:03

Eli Korvigo


People also ask

What is true bash?

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.

Is it true 1 or 0 bash?

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.

What does true do in Linux?

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.

How use true and false in Linux?

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.


1 Answers

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.

like image 131
jwodder Avatar answered Sep 30 '22 18:09

jwodder