0

I'm trying to pull array items from source file but it is failing. Here is the scenario: Main Script:

array=source_file

read -p "Array Name:" -e user_input

# pull data from source file
if [ -f ${array} ]; then
  . ${array}
fi

# display all arrays names from the source file
for a in $(grep '=' "${array}" | cut -d "=" -f 1) do
  echo "${a}"
done

Array source file:

array1=(item1 item2 item3)
array2=(item1 item2 item3)

If I add to source script following line with static entry it will display all items from selected array

for b in ${array1[@]}; do
  echo "${b}"
done

However I cannot figured out how to match user_input with the arrays in the source_file and display all items from selected array name. I was trying to do following but it displays only array name

for c in $(grep '=' "${array}" | cut -d "=" -f 1); do
  if [ "${c}" == "${user_input}" ]; then
    echo "${c}"    # <--() this displays only array name
  
    # if I use this static entry it works but this static entry must be replaced with user_input
    for d in ${array1[*]}; do
      echo "${d}"
    done
  fi
done

Question: How to replace this static entry with user_input so it shows all items from selected array?

In example with the c I was also trying to replace "for d in ${array1[*]}; do" with:

for d in ${ $(grep $user_input $array | cut -d "=" -f 1)[*]}; do
  echo "${d}"
done

but I'm missing here something as result is "bad substitution"

Any ides how to fix that?

  • `${!user_input}` – Barmar Nov 13 '21 at 10:11
  • To clarify, you have a number of arrays in a bash source file, and you want to print the array selected by the user (who inputs a name like `array1`)? Is that right? Also, are they all numbered? Would selecting a number be a better option? – dan Nov 13 '21 at 10:12
  • @Barmar that's not quite the full solution for an array. The correct answer is in the linked duplicate though. Do `user_input=${user_input}'[@]'`, then you can do `selected_array=("${!user_input}")`, or simply print with `printf '%s\n' "${!user_input}"`. You should also check input contains only valid name characters: `[[ "$user_input" == *[^[:alnum:]_]* ]] && exit 1`. – dan Nov 13 '21 at 10:30
  • If there array file is larger, you can also do `. < – dan Nov 13 '21 at 10:37

0 Answers0