Bash Booleans

I keep getting these slightly wrong, and finally got annoyed enough to write a program which produces a cheatsheat.

In [] conditional expressions, presence counts rather than value.
if [ 0 ]: true
if [ 1 ]: true
if [ ]: false
if [ "" ]: false
if [ 'abc' ]: true

In [[]] conditional expressions, the same
if [[ 0 ]]: true
if [[ 1 ]]: true
if [[ ]]: illegal
if [[ "" ]]: false
if [[ 'abc' ]]: true

In (()) arithmetic expressions, numeric value counts
if (( )): false
if (( 0 )): false
if (( 1 )): true
if (( 3 == 3 )): true
if (( 1 && 1 )): true
if (( 1 && 0 )): false
if (( 1 || 1 )): true
if (( 0 || 1 )): true
if (( 0 || 0 )): false
if (( aaa )): false
if (( '' )): false

In straight if statements, program return values are used, NOT other things
But remember that 0 is true and 1 is false.
if true : true
if false: false
if 0: illegal (no program 0)
if 1: illegal (no program 1)
if true && true: true
if true && false: false
if false || true: true
if false || false: false

Leave a Reply