2016-03-20 46 views
4

グローバル変数を効果的に使用する方法を理解できない。私がbashを理解したことから、明示的にローカルとして宣言されていない限り、すべての変数はグローバルである:http://tldp.org/LDP/abs/html/localvar.html。このように、私の理解では、私はこのような機能を構築した場合だった:Bash - 関数の配列を返す

# This function will determine which hosts in network are up. Will work only with subnet /24 networks 
is_alive_ping() # Declare the function that will carry out given task 
{ 
    # declare a ip_range array to store the range passed into function 
    declare -a ip_range=("${!1}") 

    # declare active_ips array to store active ip addresses 
    declare -a active_ips 

    for i in "${ip_range[@]}" 
    do 
    echo "Pinging host: " $i 
    if ping -b -c 1 $i > /dev/null; then # ping ip address declared in $1, if succesful insert into db 

     # if the host is active add it to active_ips array 
     active_ips=("${active_ips[@]}" "$i") 
     echo "Host ${bold}$i${normal} is up!" 

    fi 
    done 
} 

私はis_alive_ping関数の呼び出しが呼ばれた後active_ips変数へのアクセスを得ることができる必要があります。同様に:

# ping ip range to find any live hosts 
is_alive_ping ip_addr_range[@] 
echo ${active_ips[*]} 

これはさらに、この質問によってstackoverflow:Bash Script-Returning array from functionで強化されました。しかし、私のactive_ips配列のエコーは何も返しません。アレイに実際にいくつかのIPが含まれていることがわかっているので、これは私には驚くべきことです。なぜこれが失敗しているのかについてのアイデアはありますか?

答えて

3

declareはローカル変数を作成します。グローバル化するにはdeclare -gを使用するか、declareというキーワードをスキップしてください。

declare -ga active_ips 
# or 
active_ips=() 

また、あなたは+=で、配列に追加することができます迅速な応答を

active_ips+=("$i") 
+0

感謝を!私はこれを試してみましょう – NSaid

関連する問題