1

How do I import the results of a subshell command into an array in bash 3?

I have been using mapfile to accomplish this in bash 4 as follows:

mapfile -t myarray < <(someScript.sh)

However, some of the servers I am working with only have bash 3 installed, and cannot be upgraded to bash 4.

What is an equivalent command in bash 4?

I need to be able to iterate the lines in the array, and perform operations on the contents of each line.

  • "perform operations" ? what kind of operations ? if you're just processing text then an array is one of the last things you'd want to use... – don_crissti Dec 23 '16 at 0:15
  • @don_crissti I need to do regular expression checks on each line of the array. Then, if a given line contains a given regular expression, I need to do some string parsing to process dates, look for substrings, perform math on extracted numbers, etc. – CodeMed Dec 23 '16 at 1:34
  • Sounds like a job for awk but then, without knowing the exact details it's hard to tell. Anyway, if you get familiar with awk, you'll be able to do a lot of that stuff without using shell loops and arrays to process text which, as Stéphane said here, is a sign of bad coding practice. – don_crissti Dec 23 '16 at 13:42
  • @don_crissti The shell calls a second script using a subshell. All of the terminal output from the second script is checked line by line for a few different RegEx matches. If a specific RegEx match is found, the line is parsed to extract a variable. Then the value of the extracted variable is used to guide the control flow. – CodeMed Dec 23 '16 at 23:56
1

A variant of @NarūnasK's

readarray() {
  local i=0
  unset -v "$1"
  while IFS= read -r "$1[i++]"; do :; done
  eval "[[ \${$1[--i]} ]]" || unset "$1[i]"
}

Example:

$ readarray a < <(seq 10)
$ printf '%s\n' "${a[2]}"
3
1

Potentially you can replace it with simple while loop:

function map_my_array()
{
  my_file=$1
  local i=0
  while IFS='' read -r line || [[ -n "${line}" ]]; do
    my_array[((i++))]="${line}"
  done < "${my_file}"
}

fpath="$HOME/tst.sh"
echo 'cat /etc/passwd' > "${fpath}"
chmod +x "${fpath}"

map_my_array <("${fpath}")

echo "${my_array[3]}"
  • This does not execute the script. The echo line does not print anything.. I need it itorun the .sh file and then move what the script echoes out into the array. – CodeMed Dec 22 '16 at 23:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.