Bash - Returns an array from a function

I am having trouble understanding the efficient use of global variables. From my understanding of bash, each variable is global unless explicitly declared locally: http://tldp.org/LDP/abs/html/localvar.html . Thus, I realized that if I create such a function:

# 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
}

I should be able to access the variable active_ipsafter calling the is_alive_ping function. For example:

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

stackoverflow: Bash Script - . active_ips . , , IP-. , ?

+4
1

declare . declare -g, declare.

declare -ga active_ips
# or
active_ips=()

, +=:

active_ips+=("$i")
+3

All Articles