Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
    
The former is locally scoped, the later is not. – jordanm yesterday
    
thanks. can you explain the meaning of "locally scoped", maybe some examples? – Tim yesterday

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.

share|improve this answer
    
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 7 hours ago
    
These are very broad and sometimes controversial questions. Have a look to blogs.perl.org/users/ovid/2010/08/… and – jlliagre 5 hours ago
    
Is there something after "and" ? – Tim 5 hours ago
    
    
yes, "sometimes".... I guess I wanted to put another link after the second "and" but changed my mind. – jlliagre 4 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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