Skip to main content

include variable in another variable in bash [Resolved]

This question already has an answer here:

I am writing a loop in bash where I want to include one variable in another variable:

  printf "Number of volumes to add: "
  read -r num_volumes
  for volume_number in "$num_volumes"

Is this the correct syntax to use?

Question Credit: user99201
Question Reference
Asked August 22, 2018
Tags: bash
Posted Under: Unix Linux
2 Answers

First, when ever you're tempted to use variables like foo_1, foo_2, etc., just don't. Use an array instead:

foo[0]=123; foo[1]=456;
printf "%s\n" "${foo[@]}"

Or, if you need non-numeric keys, an associative array:

declare -A bar=()
bar[abc]=123; bar[def]=456;
for key in "${!bar[@]}"; do echo "$key: ${bar[$key]}"; done

As for your code, for volume_number in "$num_volumes" will run the loop body once, with volume_number set to the contents of num_volumes. The quotes prevent any splitting of num_volumes so there's only one word for for to loop over. Given that your prompt and variable name refer to a number of something, you probably don't even want to split, but to loop over a list of numbers:

read num
for (( i=0; i < num; i++ )); do
    vars[i]="some value for $i"

credit: ilkkachu
Answered August 22, 2018
Your Answer