Search code examples
bashintegerdeclare

What's the meaning of `declare -i` in bash? Does it restrict variable to only numbers?


Can anyone explain purpose of declare -i in bash? Is it for security so that you don't do string operations on numbers?

If I assign a string-number to a variable, I can already do mathematical functions on it, so what's the point of declare -i?


Solution

  • declare -i sets the integer attribute for a name. It doesn't affect the use of the variable at all, only assignments to the variable. The right-hand side of an assignment is treated as if it were an arithmetic expression, so that foo=3+5, foo="3 + 5", and foo=$((3 + 5)) are identical.

    In my opinion, it's not very useful, as it provides little benefit over an explicit arithmetic expression. You save 3 characters, "..." vs. $((...)), (unless you can safely leave the expression unquoted). Worse, it obscures the semantics of the assignment at the point it is actually made. (That is, when you seen an assignment, you need to look around to see if the integer attribute was set on the name before you know what the assignment actually does.)