Linux – bash – return array from function and display contents

bashlinux

After some bash self study and experimenting, I am stuck with returning an array from a function, and for the life of me can't see my error.

In short, what this should/must do is by using a function
have a function which reads in values/strings from a file, returning an array:

  • declare an array: clients
  • assign the function's return array to array clients
  • display array clients

It seems to me as if the function reads the whole file and not line by line, thus putting all strings into a single cell in the array, and I am not sure how to explicitly display clients[0] as this $(clients[0]) fails in bash code

If by an means I am doing something incorrectly, please point this out too or any suggestions on optimising this too

#!/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"

cat openvpn.log

something
anotherthing
anotherlineoftext
here is one more line
and lastly
one with 
a few spaces
nice

UPDATE
For anyone wanting to see how I resolved this:

  • declare a "global" array with

    declare -a clients
    
  • while the function executes, add values DIRECTLY to the clients array

To display a single index position of an array, ref. last line of code

echo "${clients[0]}"      or any other number >=0

Working code:

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]}"

Best Answer

Already answered here.

You should do a minimal search in google, because this was the first link returned for "bash return array"

Edit:

In bash, functions don't return values. They can return a status (the same as other programs).

So, if you want to return something, you should use global variables that are updated inside your function.

Related Question