Bash – Variables of integer type in Bash

arithmeticbashshellvariable

There are two ways to define and use variables of integer type in Bash

  • declare -i a new variable
  • use a variable in an arithmetic expression, without declaring it.

My questions:

What are the differences between the variables created by the two ways? Especially differences in their purposes, and when to use which?

Best Answer

The fact the variable is typed gives it some properties a generic variable won't have:

f() {
  v=0xff
  echo $v
  v=hello
  echo $v
  v=123a
  echo $v
}

f
declare -i v
f

will print

0xff
hello
123a

255
0
bash: 123a: value too great for base (error token is "123a")

If you are sure your variable will only contain integer values, typing it will give you some flexibility and error checking.

Related Question