2012-06-25 21 views
7

w bash, w jaki sposób zadeklarować zmienną całkowitą lokalnego, tzn coś takiego:bash - Jak zadeklarować lokalną liczbę całkowitą?

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 
} 

Gdzieś widziałem local -i number=0 używany, ale to nie wygląda bardzo przenośny.

+0

Co rozumiesz przez niezależność od platformy? Konstrukcje Bash są wszędzie takie same. –

+0

@larsmans Sry, oznaczało przenośne. – helpermethod

Odpowiedz

10

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

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

Dla każdego argumentu zmienna lokalna o nazwie nazwa jest tworzona i przypisane wartości. Opcją może być dowolna z opcji zaakceptowanych przez deklarację.

Tak local -i jest ważny.

+0

+1 Nie wiedziałem, że akceptuje te same opcje, co deklaracja. – helpermethod

+1

'local' był kiedyś aliasem' declare', więc nie jest to zaskakujące (na powłoce Korn nadal jest to alias do 'typedef'). – cdarke

9

declare wewnątrz funkcji automatycznie powoduje, że zmienna jest lokalna. Tak to działa:

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" 

a wyjście jest:

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

W przypadku skończyć się tutaj z Androidem skrypt powłoki może chcesz wiedzieć, że Android jest za pomocą MKSH a nie pełną Bash, która ma pewne efekty. Sprawdź to:

#!/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 to, otrzymujemy:

# 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 

Zatem w Androidadeclare nie istnieje. Ale czytając, pozostałe powinny być równoważne.

Powiązane problemy