Reputation: 87
How can I access an element of an array in bash using a variable as its name? The idea is that I want to select the array that I want by passing its name as an argument when I run my script. So I was thinking I could do something like this something like this:
#!/usr/bin/env bash
arrName=$1
g=(1 32)
g5=(5 32)
m=(1 12)
m15=(1 12)
echo "${!arrName[0]}"
echo "${!arrName[1]}"
But while this prints the first element of the array, it fails to print the second one. E.g.:
./myScript g
returns:
1
# The second line just has a new line character
Can you please explain what is going on as well as the proper way to do this (if any)?
Upvotes: 1
Views: 81
Reputation: 530960
Indirection involving array elements requires a temporary variable whose value is the name of the array plus the desired index.
arrName=$1
g=(1 32)
g5=(5 32)
m=(1 12)
m15=(1 12)
tmp0="$arrName[0]"
tmp1="$arrName[1]"
echo "${!tmp0}"
echo "${!tmp1}"
That said, namerefs are easier to follow when available.
Upvotes: 1
Reputation: 84531
Indirection does not work with array names. You need to create a nameref using declare -n arrName="$1"
and then remove the '!'
from your echo
statements, e.g.
#!/bin/bash
declare -n arrName="$1"
g=(1 32)
g5=(5 32)
m=(1 12)
m15=(1 12)
echo "${arrName[0]}"
echo "${arrName[1]}"
Example Use/Output
bash nr.sh g
1
32
Upvotes: 1