NSaid
NSaid

Reputation: 751

Return array from a Bash function

I am having trouble understanding how to use global variables effectively. From my understanding of bash, every variable is global unless explicitly declared local as per: http://tldp.org/LDP/abs/html/localvar.html. Thus, my understanding was if I build a function like this:

# 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 get access to the active_ips variable once the call to is_alive_ping function has been called. Like so:

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

This was further reinforced by this question in stackoverflow: Bash Script-Returning array from function. However my echo for the active_ips array returns nothing. This is surprising to me because I know the array actually contains some IPs. Any ideas as to why this is failing?

Upvotes: 6

Views: 4951

Answers (1)

John Kugelman
John Kugelman

Reputation: 361575

declare creates local variables. Use declare -g to make them global, or just skip the declare keyword altogether.

declare -ga active_ips
# or
active_ips=()

Also, you can append to array with +=:

active_ips+=("$i")

Upvotes: 4

Related Questions