How to use a variable to index $ {array [*]} in bash?

First of all, sorry, because my English may not be very good. I want to use a variable to index an element in an array or use the same variable to index all elements. For instance:

...
var1="1"
var2="*"
array=(one two three for five)

for elem in ${array[$var1]}
do
  echo $elem
done

When I use var1 to index into $ {array [$ var1]} , it works correctly, but if I use var2, it does not work correctly, I get this error:

./ed.sh line XXX *: syntax error: operand expected (error token is "*")

I am sure that the error is related to the expansion of substitution *, but I did not find an answer that will help me solve this problem. So how can I do this?

+4
source share
2 answers

* @ . .

bash chk_atstar, , [@] [*], , , - :

else if (valid_array_reference (name, 0))
  {
    temp1 = mbschr (name, '[');
    if (temp1 && temp1[1] == '@' && temp1[2] == ']')
      {

, :

arr=(one two three)
index='*'
var="arr[$index]"
echo "${!var}"

.

+4

, , eval:

eval items=\${array[$var2]}
for elem in $items
do
    echo $elem
done

. eval "", . , , eval. .

, . :

array+=('at the end')

, , .

EDIT: , eval, ( ). :

display_it() {
    if [[ $1 = '*' ]]; then
        oldIFS="$IFS"
        IFS=$'\n'
        echo "${array[*]}"
        IFS="$oldIFS"
    else
        echo "${array[$1]}"
    fi
}

var1="1"
var2="*"
array=(one two three for five)
array+=('at the end')

while read -r elem
do
  echo $elem
done < <(display_it "$var2")

:

one
two
three
for
five
at the end

, display_it. , , (IFS).

+1

Source: https://habr.com/ru/post/1692998/


All Articles