logical operator

Last edit

Changed:

< }}}

to

> }}}


In awk, *logical operators* are used to perform [[boolean?]] operations, and a return a value of [true] or [false], depending on the values of the [operand]s.

*Operator**Symbol**Description*
[[and?]][[doubleampersand_&&?]]Returns [true] if both [[operand?]]s are [[true?]], otherwise returns [[false?]]
[[or?]][[doublepipe?]]Returns [[true?]] if either or both [[operand?]]s are [[true?]], otherwise returns [[false?]]
[[not?]][[pling !]]Returns [[false] if [[operand?]] is [[true?]], otherwise returns [[true?]]

Traditionally, awk does not provide a logical [[xor?]] operator

Results of Logical Operations

The [[logical?]] operators return a [[boolean?]] value of 0 for [[false?]], and 1 for [[true?]]. In awk, the null strings "" are treated as [[false?]] expressions, a non null string is true:

 print (0 && 0)                 # 0 (false)
 print (0 && 7)                 # 0 (false)
 print (7 && 0)                 # 0 (false)
 print (7 && 2)                 # 1 (true)
 print (2 && 7)                 # 1 (true)
 print ("" && "")               # 0 (null strings are treated as false)
 print ("apples" && "pears")    # 1 (true)

 print (0 || 7)                 # 1 (true)
 print (7 || 0)                 # 1 (true)
 print (7 || 2)                 # 1 (true)
 print (2 || 7)                 # 1 (true)
 print ("" || "")               # 0  (null strings are treated as false)
 print ("apples" || "pears")    # 1 (true)

Precedence

The unary [[NOT?]] operator has a higher precedence than the dyadic [[AND?]] and [[OR?]] operators:

Associativity

The [[dyadic?]] logical operators have left [[associativity?]], which means that the left hand [[operand?]] is evaluated before the right hand [[operand?]].

NOT Operator has right hand associativity

The unary [[NOT?]] operator, has right hand [associativity]:

Conditional Branching

Logical operators may be used within a program to create [[conditional_branching?]] structures.

Expressions Containing Multiple Operators

Confusion Between Logical and Bitwise Operators


[[Logical_Operator_Precedence?]]

[[Conditional_Branching_Using_Logical_Operators?]]

[[Logical_Operators_with_Strings?]]

[[Logical_Operator_Efficiency?]]

[[Logic_Optimization?]]

truth