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?
BASH Cannot Return an Array! Sadly, despite all the advantages In order to break up the task of collecting all the necessary parameters for a YAD call, it is helpful to call several functions to build up the arrays. However, BASH lacks the ability to return arrays from functions.
A bash function can return a value via its exit status after execution. By default, a function returns the exit code from the last executed command inside the function. It will stop the function execution once it is called. You can use the return builtin command to return an arbitrary number instead.
Example: Bash function returns multiple values, passed via command substitution, with a READ command and Here string in calling script #bash #bash_exemplar · GitHub.
In short, we cannot export an BASH array. Exporting not only does no good but also may incur issues (trigger a bug of bash?).
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With