Illustrating the Quirks of Bash Duck Typing

The aim of this page📝 is to stress that all bash variables are character strings which can lead to unexpected behavior. There are no objects (e.g. PowerShell or Python object-based) although all three of them are dynamically typed languages. Also, these are my footnotes under Bash Variables Are Untyped.

Pavol Kutaj
1 min readDec 9, 2022

the king and queen of types are strings and integers, of course

  • bash evaluates the context
  • then, if appropriate, it treats characters as numbers
  • meaning it permits arithmetic operations and comparisons of variables
  • the determining factor is if the value of a variable contains only digits

there are quirks in bash duck typing that are not present in object-based python/PowerShell

  • if you try to add 1 to a string, a TypeError gets raised
>>> not_integer = "foobar"
>>> not_integer += 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
  • in Bash, however, the string is silently reset
not_int="foo"
let "not_int += 1"
echo $not_int

the ‘let’ command does exactly what (( )) does — evaluates arithmetic expression

  • Instead of let expr, prefer (( expr ))

The (( .. )) arithmetic compound command evaluates expressions in the same way as let, except it’s not subject to glob expansion and therefore requires no additional quoting or escaping.

$ a=1
$ let a++
$ echo $a
2
$ (( a++ ))
$ echo $a
3

--

--

No responses yet