3

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?

  • The former is locally scoped, the later is not. – jordanm Apr 23 '16 at 21:45
  • thanks. can you explain the meaning of "locally scoped", maybe some examples? – Tim Apr 23 '16 at 21:47
7

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.

  • Thanks. (1) What are the definitions of "untyped" and "typed" variables in general sense for programming languages? Is an untyped variable defined as a variable whose type can be changed implicitly according to the context? For a typed variable, can we change its type, and if yes, do we have to do it explicitly (like type conversion in C or C++)? (2) Is a "dynamically typed" variable defined as a variable whose type is not changeable implicitly (i.e. the variable is typed), and is determined dynamically at run time? – Tim Apr 24 '16 at 18:26
  • These are very broad and sometimes controversial questions. Have a look to blogs.perl.org/users/ovid/2010/08/… and – jlliagre Apr 24 '16 at 20:38
  • Is there something after "and" ? – Tim Apr 24 '16 at 21:07
  • yes, "sometimes".... I guess I wanted to put another link after the second "and" but changed my mind. – jlliagre Apr 24 '16 at 21:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.