经过一些 bash 自学和试验,我坚持从函数返回一个数组,并且我一生都看不到我的错误。
简而言之,这应该/必须做的是使用具有从文件中读取值/字符串的函数,返回一个数组:
在我看来,该函数似乎读取整个文件而不是逐行读取,从而将所有字符串放入数组中的单个单元格中,我不确定如何将 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)
更新 对于任何想了解我如何解决此问题的人:
声明一个“全局”数组
declare -a clients
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)
归档时间: |
|
查看次数: |
29423 次 |
最近记录: |