2012-06-25 16 views
7

在bash中,我怎麼聲明一個局部整型變量,即是這樣的:bash - 如何聲明一個本地整數?

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 
} 

帶我看了local -i number=0被使用,但是這看起來不是很便攜。

+0

平臺無關是什麼意思? Bash builtins在任何地方都是一樣的。 –

+0

@larsmans Sry,意思是便攜式。 – helpermethod

回答

10

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

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

對於每一個參數,一個本地命名名稱變量創建並分配值。該選項可以是declare接受的任何選項。

因此local -i是有效的。

+0

+1不知道它接受與聲明相同的選項。 – helpermethod

+1

'local'曾經是'declare'的別名,所以這並不奇怪(在Korn shell中它仍然是'typedef'的別名)。 – cdarke

9

declare裏面的一個函數自動使變量局部。所以這個工程:

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" 

,輸出是:

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

如果你會在這裏結束與Android的shell腳本,你可能想知道Android是使用MKSH並沒有滿擊,這有一些效果。檢查了這一點:

#!/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; 

運行此,我們得到:

# 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 

因此,在的Androiddeclare不存在。但是閱讀起來,其他人應該是相同的。