Assign variable on array with loop in Bash Script

I have four variables, seen below:

p0="something"
p1="something"
p2="something"
p3="something"
p4="something"

var=()

I want to put each of the variables into an array with a loop, in a way so that I can call the value of the variable within the array. It should look something like this:

var=($p0 $p1 $p2 $p3 p$4)

I already tried this:

for i in {0..4}
do
    $var[$i]="\$p$i"
done

but that doesn't work.

Upvotes: 1

Views: 675

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52142

You could use namerefs (Bash 4.3+) and the ${!prefix@} parameter expansion:

declare -n varname
for varname in "${!p@}"; do
    var+=("$varname")
done

This makes varname behave as if it were the variable its name it has as its value; "${!p@}" expands to all variable names with prefix p. This is also a drawback of this method: it fails if there are other variables whose name starts with p.

A more explicit way would be to loop over the variable names like this:

for varname in p{0..4}; do

Upvotes: 3

Related Questions