Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting | ||
---|---|---|
Prev | Chapter 5. Introduction to Variables and Parameters | Next |
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 5-4. Integer or string?
1 #!/bin/bash 2 # int-or-string.sh 3 # Integer or string? 4 5 a=2334 # Integer. 6 let "a += 1" 7 echo "a = $a " # Integer, still. 8 echo 9 10 b=${a/23/BB} # Transform into a string. 11 echo "b = $b" # BB35 12 declare -i b # Declaring it an integer doesn't help. 13 echo "b = $b" # BB35, still. 14 15 let "b += 1" # BB35 + 1 = 16 echo "b = $b" # 1 17 echo 18 19 c=BB34 20 echo "c = $c" # BB34 21 d=${c/BB/23} # Transform into an integer. 22 echo "d = $d" # 2334 23 let "d += 1" # 2334 + 1 = 24 echo "d = $d" # 2335 25 26 # Variables in Bash are essentially untyped. 27 28 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.