bash - 从函数返回数组并显示内容

Cyb*_*beX 6 linux bash

经过一些 bash 自学和试验,我坚持从函数返回一个数组,并且我一生都看不到我的错误。

简而言之,这应该/必须做的是使用具有从文件中读取值/字符串的函数,返回一个数组:

  • 声明一个数组:clients
  • 将函数的返回数组分配给数组客户端
  • 显示阵列客户端

在我看来,该函数似乎读取整个文件而不是逐行读取,从而将所有字符串放入数组中的单个单元格中,我不确定如何将 clients[0] 显式显示为 $(clients[0] ]) 在 bash 代码中失败

如果通过某种方式我做错了什么,也请指出这一点或任何关于优化这一点的建议

#!/bin/bash
readArray(){
        local array=()
        local i=0;
        local j=0
        while IFS= read -r LINE  && [[ -n "$LINE" ]] ; do 
                array[$((i++))]+=${LINE}; # Append line to the array
                ((j++))
        done < "$1";
        rtr=${array[@]}
}
string="/home/cybex/openvpntest/openvpn.log"
declare -a clients
#sed -i '/^$/d' $string
clients=$(readArray "$string")
echo "${clients[@]}"

echo -e "array not empty, displaying array contents\n"

for i in "${!clients[@]}"; do 
  echo "$i: ${clients[$i]}"
done
echo -e "\nfinished displaying contents of array"
Run Code Online (Sandbox Code Playgroud)

猫 openvpn.log

something
anotherthing
anotherlineoftext
here is one more line
and lastly
one with 
a few spaces
nice
Run Code Online (Sandbox Code Playgroud)

更新 对于任何想了解我如何解决此问题的人:

要显示数组的单个索引位置,请参考。最后一行代码

echo "${clients[0]}"      or any other number >=0
Run Code Online (Sandbox Code Playgroud)

工作代码:

declare -a clients
readArray(){
        local array=()
        local i=0;
        local j=0
        while IFS= read -r LINE  && [[ -n "$LINE" ]] ; do 
                clients[$((i++))]+=${LINE}; # Append line to the array
                ((j++))
        done < "$1";
}
string="/home/cybex/openvpntest/openvpn.log"
sed -i '/^$/d' $string
readArray "$string"
echo "${clients[@]}"

echo -e "array not empty, displaying array contents\n"

for i in "${!clients[@]}"; do 
  echo "$i: ${clients[$i]}"
done
echo -e "\nfinished displaying contents of array"
echo "${clients[0]}"
Run Code Online (Sandbox Code Playgroud)

cri*_*sti 5

这里已经回答了。

您应该在谷歌中进行最少的搜索,因为这是为“bash return array”返回的第一个链接

编辑:

在 bash 中,函数不返回值。它们可以返回状态(与其他程序相同)。

因此,如果您想返回某些内容,则应该使用在函数内更新的全局变量。