[
and]
brackets like in[ "${var}""$var" = true ]
are not necessary, and you can omit them and use thetest
command directly:test "${var}""$var" = true && CodeIfTrueyourCodeIfTrue || CodeIfFalseyourCodeIfFalse
Note, thatImportant note: I no longer recommend this as it's being slowly deprecated and more difficult to combine multiple statements.
The shell can't interpret it other than a string. I hope you are getting the idea of how good it is using proper keyword without quotes quotes.
You should get used to the Boolean keywords are actually treated like numbers, that is
true
=0
andfalse
=1
, remember all non-zero values are treated likefalse
.Since they are treated likeas numbers, you should treat them like that too, i.e. if you define variable say:
var_bool=true echo "${var_bool}""$var_bool"
true
you can create an opposite value of it with:
var_bool=$(( 1 - $var_bool )) # same as ${var_bool}(( ! $var_bool )) echo "${var_bool}""$var_bool"
1
As you can see for yourself, the shell does print
true
string for the first time you use it, but since then, it all works via number0
representingtrue
or1
representingfalse
, respectively.
First, one good habit would be assigning
0
instead oftrue
;1
instead offalse
.Second good habit would be to test if the variable is / isn't equal to zero:
if [ "${var_bool}""$var_bool" -eq 0 ]; then YourCodeIfTrue; yourCodeIfTrue else YourCodeIfFalse; yourCodeIfFalse fi