| 1 | #!/bin/bashscip-shell filesystem . . `/bin/bash`. |
| 2 | # int-or-string.sh |
| 3 | |
| 4 | a=2334 # Integer. |
| 5 | let "a += 1" |
| 6 | echoscip-shell system . . echo. "a = $a " # a = 2335 |
| 7 | echoscip-shell system . . echo. # Integer, still. |
| 8 | |
| 9 | |
| 10 | b=${a/23/BB} # Substitute "BB" for "23". |
| 11 | # This transforms $b into a string. |
| 12 | echoscip-shell system . . echo. "b = $b" # b = BB35 |
| 13 | declare -i b # Declaring it an integer doesn't help. |
| 14 | echoscip-shell system . . echo. "b = $b" # b = BB35 |
| 15 | |
| 16 | let "b += 1" # BB35 + 1 |
| 17 | echoscip-shell system . . echo. "b = $b" # b = 1 |
| 18 | echoscip-shell system . . echo. # Bash sets the "integer value" of a string to 0. |
| 19 | |
| 20 | c=BB34 |
| 21 | echoscip-shell system . . echo. "c = $c" # c = BB34 |
| 22 | d=${c/BB/23} # Substitute "23" for "BB". |
| 23 | # This makes $d an integer. |
| 24 | echoscip-shell system . . echo. "d = $d" # d = 2334 |
| 25 | let "d += 1" # 2334 + 1 |
| 26 | echoscip-shell system . . echo. "d = $d" # d = 2335 |
| 27 | echoscip-shell system . . echo. |
| 28 | |
| 29 | |
| 30 | # What about null variables? |
| 31 | e='' # ... Or e="" ... Or e= |
| 32 | echoscip-shell system . . echo. "e = $e" # e = |
| 33 | let "e += 1" # Arithmetic operations allowed on a null variable? |
| 34 | echoscip-shell system . . echo. "e = $e" # e = 1 |
| 35 | echoscip-shell system . . echo. # Null variable transformed into an integer. |
| 36 | |
| 37 | # What about undeclared variables? |
| 38 | echoscip-shell system . . echo. "f = $f" # f = |
| 39 | let "f += 1" # Arithmetic operations allowed? |
| 40 | echoscip-shell system . . echo. "f = $f" # f = 1 |
| 41 | echoscip-shell system . . echo. # Undeclared variable transformed into an integer. |
| 42 | # |
| 43 | # However ... |
| 44 | let "f /= $undecl_var" # Divide by zero? |
| 45 | # let: f /= : syntax error: operand expected (error token is " ") |
| 46 | # Syntax error! Variable $undecl_var is not set to zero here! |
| 47 | # |
| 48 | # But still ... |
| 49 | let "f /= 0" |
| 50 | # let: f /= 0: division by 0 (error token is "0") |
| 51 | # Expected behavior. |
| 52 | |
| 53 | |
| 54 | # Bash (usually) sets the "integer value" of null to zero |
| 55 | #+ when performing an arithmetic operation. |
| 56 | # But, don't try this at home, folks! |
| 57 | # It's undocumented and probably non-portable behavior. |
| 58 | |
| 59 | |
| 60 | # Conclusion: Variables in Bash are untyped, |
| 61 | #+ with all attendant consequences. |
| 62 | |
| 63 | exit $? |