bash - How to declare a local integer?

22,188

Solution 1

Per http://www.gnu.org/software/bash/manual/bashref.html#Bash-Builtins,

local [option] name[=value] ...

For each argument, a local variable named name is created, and assigned value. The option can be any of the options accepted by declare.

So local -i is valid.

Solution 2

declare inside a function automatically makes the variable local. So this works:

func() {
    declare -i number=0
    number=20
    echo "In ${FUNCNAME[0]}, \$number has the value $number"
}
number=10
echo "Before the function, \$number has the value $number"
func
echo "After the function, \$number has the value $number"

And the output is:

Before the function, $number has the value 10
In func, $number has the value 20
After the function, $number has the value 10

Solution 3

In case you end up here with an Android shell script you may want to know that Android is using MKSH and not full Bash, which has some effects. Check this out:

#!/system/bin/sh
echo "KSH_VERSION:  $KSH_VERSION"
local -i aa=1
typeset -i bb=1
declare -i cc=1
aa=aa+1;
bb=bb+1;
cc=cc+1;
echo "No fun:"
echo "  local   aa=$aa"
echo "  typset  bb=$bb"
echo "  declare cc=$cc"
myfun() {
    local -i aaf=1
    typeset -i bbf=1
    declare -i ccf=1
    aaf=aaf+1;
    bbf=bbf+1;
    ccf=ccf+1;
    echo "With fun:"  
    echo "  local   aaf=$aaf"
    echo "  typset  bbf=$bbf"
    echo "  declare ccf=$ccf"
}
myfun;

Running this, we get:

# woot.sh
KSH_VERSION:  @(#)MIRBSD KSH R50 2015/04/19
/system/xbin/woot.sh[6]: declare: not found
No fun:
  local   aa=2
  typset  bb=2
  declare cc=cc+1
/system/xbin/woot.sh[31]: declare: not found
With fun:
  local   aaf=2
  typset  bbf=2
  declare ccf=ccf+1

Thus in Android declare doesn't exist. But reading up, the others should be equivalent.

Share:
22,188

Related videos on Youtube

helpermethod
Author by

helpermethod

Updated on April 13, 2020

Comments

  • helpermethod
    helpermethod over 2 years

    In Bash, how do I declare a local integer variable, i.e. something like:

    func() {
      local ((number = 0)) # I know this does not work
      local declare -i number=0 # this doesn't work either
      # other statements, possibly modifying number
    }
    

    Somewhere I saw local -i number=0 being used, but this doesn't look very portable.

    • Fred Foo
      Fred Foo
      What do you mean by platform-independent? The Bash builtins are the same everywhere.
  • cdarke
    cdarke over 10 years
    local used to be an alias to declare, so it is not surprising (on Korn shell it still is an alias to typedef).
  • meso_2600
    meso_2600 over 3 years
    but local and declare are so much different :)

Related