0

I have a function that reads a text file containing a list of tests and returns an array with each line being a separate element in the array

the file contains:

existing_user_test
new_user_test "approved"
random_user_test

here is the code

test_list=( $(get_test_list $test_list_file) )
   
for i in ${!test_list[@]}; do echo ${test_list[$i]}; done

get_test_list() {
    declare -a test_list
    local test_file=$1

    while IFS= read -r line; do        
        test_list+=("${line}")                 
    done < $test_file

    echo "${test_list[@]}"  # return the test_list array
}

This works great for all tests that have no spaces in them
However when I loop over the test_list variable - it divides the test that has a space in it into 2 elements

so its outputting

existing_user_test
new_user_test
"approved"
random_user_test

instead of

existing_user_test
new_user_test "approved"
random_user_test
cseagull
  • 33
  • 8
  • 2
    If you're going to return an arbitrary array from a function over stdout, you need to NUL-delimit its entries. Better, don't use stdout at all, pass the destination by name and have the function modify the named variable in-place. – Charles Duffy Aug 20 '23 at 13:37
  • 1
    if running `bash 4.3+` I find nameref's to be the easiest approach (if you're on macos you may need to homebrew/update to a newer version of `bash`); see the 2nd half of [this answer](https://stackoverflow.com/a/75288219) for an example; in your case you'll need to update your function to accept a 2nd argument - the name of the array you with to populate, eg, replace `test_list=( $(get_test_list $test_list_file) )` with `get_test_list test_list $test_list_file` – markp-fuso Aug 20 '23 at 14:07
  • 1
    Functions in bash **don't return anything**. Whenever you want them to simulate a return value (in your case, you have them write to stdout and require the caller to catch the stdout and parse it), you need to think of a protocol between caller and your function, how to get at the "returned" value. In your case, this protocol was badly chosedn, because the caller has no way whether a stdout of `a b c` is supposed to be an array of 3 elements `(a b c)` or is meant as an array of, say, 2 elements`(a "b c")`. Instead of "simulating returning an array", have the function filling the array itself. – user1934428 Aug 21 '23 at 07:24

0 Answers0