You deduced right, bash
variables by default contain strings, and its values are treated as strings.
You can use the declare
built-in command to explicitly say they store integers (declare -i myintvar
), or indexed arrays (declare -a myarr
), or associative arrays (declare -A mymap
), etc., but not booleans.
The closest you can get to booleans is to use integer values 0
and 1
and evaluate expressions as arithmetic expressions with the (( expr ))
command (bash
-specific), or with arithmetic expansion $(( expr ))
(POSIX-compatible). Those commands evaluate expr
according to rules of shell arithmetic.
For example:
A=1
B=0
(( C = \!A )) # logical negation ==> C = 0
(( D = A && B )) # logical AND ==> D = 0
E=$(( A ^ B )) # bitwise XOR ==> E = 1
In bash
, you can also use declare -i
and let
:
declare -i E='A||B' # equivalent to: E=$((A||B)), or ((E=A||B))
let C='!A' # equivalent to: C=$((\!A)), or ((C=\!A))
which are a longer way of saying ((..))
or $((..))
. They both force arithmetic evaluation of the expressions given.
Note that !
has a special meaning in most shells (including bash
), it causes history expansion. To prevent it, we must escape it with a backslash, or quote it.