Logical operations: Difference between revisions

→‎{{header|UNIX Shell}}: Add implementation.
(→‎{{header|Commodore BASIC}}: Add XOR from BASIC 7.)
(→‎{{header|UNIX Shell}}: Add implementation.)
Line 3,890:
 
0 OK, 0:63</pre>
 
=={{header|UNIX Shell}}==
 
The shell has at least two levels of logical operators. Conditional logic (<tt>if</tt>, <tt>while</tt>, <tt>&&</tt> and <tt>||</tt> at the statement level) operates on commands; the commands are executed, and their exit status determines their value in a Boolean context. If they return an exit code of 0, signaling successful execution, that is considered a "true" result; if they return a nonzero exit code, signaling a failure condition, that is considered a "false" result. However, these results are not returned as a Boolean value. <tt>if command; then do something; fi</tt> will do something if the commands succeeds, but there's no "true" value, only the zero exit status. So this demo uses a function that examines the exit status of the last command and prints "true" if it is 0 and "false" otherwise. The two values for the task are the <em>commands</em> <tt>true</tt> and <tt>false</tt>, which do nothing but exit with status 0 and 1, respectively.
 
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{Works with|Z Shell}}
<lang bash>function boolVal {
if (( ! $? )); then
echo true
else
echo false
fi
}
a=true
b=false
printf '%s and %s = %s\n' "$a" "$b" "$("$a" && "$b"; boolVal)"
printf '%s or %s = %s\n' "$a" "$b" "$("$a" || "$b"; boolVal)"
printf 'not %s = %s\n' "$a" "$(! "$a"; boolVal)"</lang>
{{Out}}
<pre>true and false = false
true or false = true
not true = false</pre>
 
A different variety of Boolean logic is available inside arithmetic expressions, using the C convention of 0=false and nonzero=true=1:
 
<lang bash>a=1
b=0
printf '%d and %d = %d\n' "$a" "$b" "$(( a && b ))"
printf '%d or %d = %d\n' "$a" "$b" "$(( a || b ))"
printf 'not %d = %d\n' "$a" "$(( ! a ))"</lang>
 
{{Out}}
<pre>1 and 0 = 0
1 or 0 = 1
not 1 = 0</pre>
 
 
=={{header|V}}==
1,481

edits