-1

I'm trying to assign multiple variables to load into a pipeline. I want to prompt the user for values and then read them into variables. My current script is:

echo "How many galaxies are you analyzing?"
read n1

i=1
while [$i -lt $n1]; do
echo "Please list galaxy $i."
read gal${i}
echo "How many observations are there for gal${i}?"
read n2
while [$j -lt  $n2]
echo "Please enter observation #$j for gal${i}."
read obs${j}
echo gal${i}
echo obs${j}
let j++
done
echo gal${i}
let i+1
done

I would like for there to be a tree consisting of

├── gal1
|   ├── obs1
│   └── obs2
├── gal2
│   ├── obs1
│   ├── obs2
│   └──obs3

where these values are any alphanumeric combination.

The error I'm getting when I run the loop above is:

user@user:~$ bash tst.tst 
How many galaxies are you analyzing?
2
tst.ts: line 16: syntax error near unexpected token `done'
tst.ts: line 16: `done'
wjandrea
  • 14,236
  • 4
  • 48
  • 98
J. Doe
  • 333

1 Answers1

1

First, indent your code so it's logical structure is more easily viewed (many editors will do this for you, but it's worth doing manually if you must):

#!/bin/bash
echo "How many galaxies are you analyzing?"
read n1

i=1
while [[ $i -lt $n1 ]]; do
    echo "Please list galaxy $i."
    read gal${i}
    echo "How many observations are there for gal${i}?"
    read n2
    while [[ $j -lt  $n2 ]] ; do
        echo "Please enter observation #$j for gal${i}."
        read obs${j}
        echo gal${i}
        echo obs${j}
        let j++
    done
    echo gal${i}
    let i+1
done

Second, the first line should be "#!/bin/bash".

Third, line while [$j -lt $n2] needs a ; do after it.

Fourth, using [ runs /usr/bin/test every time. Using the bash builtin [[ (and ]]) is better.

"I would like for there to be a tree...". It's a SMOP (Simple Matter of Programming), and you will have to arrange the data the way you need it. However, building trees in bash is unecessarily hard, when perl, python, ruby, etc exist.

waltinator
  • 36,399
  • Also note that the test commands [ and [[ need spaces, like [ $j -lt $n2 ] and [[ $j -lt $n2 ]] – wjandrea Jul 20 '18 at 22:43
  • @wjandrea Thank you for the reminder - I changed my answer. – waltinator Jul 20 '18 at 22:49
  • "Fourth, using [ runs /usr/bin/test every time" - not AFAIK at least in bash, dash, or ksh (run type [ if in doubt - it should be a shell builtin in all cases). [[ . . .]] still has advantages but probably the right operators to use for arithmetic comparison in modern bash are (( . . .)) e.g. while ((j < n2)); do – steeldriver Jul 20 '18 at 22:58