0

I'm trying to make a nested variable prompt for loop in Bash. However, I get the error bad substitution.

#! /bin/bash

echo "how many sources?"
read NumSour

for (( i=1; i<=$NumSour; i++ ))
        do
        echo "what is the wavelength of source" ${i}"?"
        read Wave${i}

        for j in Wave${i}
                do
                echo ${Wave${i}} 
                done
        done

I want to prompt how many variables, then assign each of those variables with a value. Then print the variables’ values.

Echoing ${j} gives Wave1, Wave2, etc. not the values of the variables.

I tried switching to format of the second for loop with the same as the first for loop, but it iterates over the values of the variables.

for (( i=1; i<=$NumSour; i++ ))
        do
        echo "what is the wavelength of source" ${i}"?"
        read Wave${i}

        for (( j=Wave1; j<=Wave${i}; j++ ))
                do
                echo ${j}
                done
        done

Say Wave1 is 1 and Wave2 is 4, it echos 1, 2, 3, and 4. I need it to just echo 1 and 4.

Biffen
  • 6,249
  • 6
  • 28
  • 36
  • Welcome to stackoverflow! Put a valid [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) and paste your script at https://shellcheck.net for validation/recommendation. – Jetchisel May 24 '23 at 03:56
  • 3
    Using dynamic variable names like you're trying to is messy and hard to get right. I'd recommend using an array instead: `read Wave[i]` and `for (( j=Wave[1]; j<=Wave[i]; ...`. This is the sort of thing arrays are for. – Gordon Davisson May 24 '23 at 04:41
  • `${Wave${i}}` is not valid bash. – user1934428 May 24 '23 at 05:58

0 Answers0