我无法理解如何有效地使用全局变量。根据我对 bash 的理解,除非按照http://tldp.org/LDP/abs/html/localvar.html明确声明为本地变量,否则每个变量都是全局变量。因此,我的理解是,如果我构建这样的函数:
# 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
}
Run Code Online (Sandbox Code Playgroud)
active_ips一旦调用 is_alive_ping 函数,我应该能够访问该变量。像这样:
# ping ip range to find any live hosts
is_alive_ping ip_addr_range[@]
echo ${active_ips[*]}
Run Code Online (Sandbox Code Playgroud)
stackoverflow 中的这个问题进一步强化了这一点:Bash Script-Returning array from function。但是,我对 active_ips 数组的回显什么也不返回。这让我感到惊讶,因为我知道数组实际上包含一些 IP。关于为什么会失败的任何想法?
declare创建局部变量。使用declare -g使它们成为全局的,或者完全跳过declare关键字。
declare -ga active_ips
# or
active_ips=()
Run Code Online (Sandbox Code Playgroud)
另外,您可以使用以下命令附加到数组+=:
active_ips+=("$i")
Run Code Online (Sandbox Code Playgroud)