1

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.

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.