4.3. Bash Variables Are Untyped

Unlike many other programming languages, Bash does not segregate its variables by "type". Essentially, Bash variables are character strings, but, depending on context, Bash permits integer operations and comparisons on variables. The determining factor is whether the value of a variable contains only digits.


Example 4-4. Integer or string?

   1 #!/bin/bash
   2 # int-or-string.sh: Integer or string?
   3 
   4 a=2334                   # Integer.
   5 let "a += 1"
   6 echo "a = $a "           # a = 2335
   7 echo                     # Integer, still.
   8 
   9 
  10 b=${a/23/BB}             # Substitute "BB" for "23".
  11                          # This transforms $b into a string.
  12 echo "b = $b"            # b = BB35
  13 declare -i b             # Declaring it an integer doesn't help.
  14 echo "b = $b"            # b = BB35
  15 
  16 let "b += 1"             # BB35 + 1 =
  17 echo "b = $b"            # b = 1
  18 echo
  19 
  20 c=BB34
  21 echo "c = $c"            # c = BB34
  22 d=${c/BB/23}             # Substitute "23" for "BB".
  23                          # This makes $d an integer.
  24 echo "d = $d"            # d = 2334
  25 let "d += 1"             # 2334 + 1 =
  26 echo "d = $d"            # d = 2335
  27 echo
  28 
  29 # What about null variables?
  30 e=""
  31 echo "e = $e"            # e =
  32 let "e += 1"             # Arithmetic operations allowed on a null variable?
  33 echo "e = $e"            # e = 1
  34 echo                     # Null variable transformed into an integer.
  35 
  36 # What about undeclared variables?
  37 echo "f = $f"            # f =
  38 let "f += 1"             # Arithmetic operations allowed?
  39 echo "f = $f"            # f = 1
  40 echo                     # Undeclared variable transformed into an integer.
  41 
  42 
  43 
  44 # Variables in Bash are essentially untyped.
  45 
  46 exit 0

Untyped variables are both a blessing and a curse. They permit more flexibility in scripting (enough rope to hang yourself!) and make it easier to grind out lines of code. However, they permit errors to creep in and encourage sloppy programming habits.

The burden is on the programmer to keep track of what type the script variables are. Bash will not do it for you.

AskApache Web Development