0

I'm having some trouble writing a command that includes a String of a variable in Bash and wanted to know the correct way to do it.

I want to try and fill the Row arrays with the numbers 1-9 but I'm getting myself stuck when trying to pass a variable Row$Line[$i]=$i.

Row0=()
Row1=()
Row2=()

FillArrays() {
for Line in $(seq 0 2)
do
    for i in $(seq 1 9)
    do
        Row$Line[$i]=$i
    done
done

}

I can get the desired result if I echo the command but I assume that is just because it is a String.

I want the for loop to select each row and add the numbers 1-9 in each array.

2
  • FYI, it's generally better to avoid seq (which isn't part of bash, or defined by the POSIX standard; thus, whether it exists is up to the host OS). Consider for ((Line=0; Line<2; line++)); do Commented Sep 3, 2019 at 15:02
  • ...that said, what you're trying to do is called indirect assignment. Commented Sep 3, 2019 at 15:02

2 Answers 2

3
FillArrays() {
  for ((Line=0; Line<8; Line++)); do
    declare -g -a "Row$Line"          # Ensure that RowN exists as an array
    declare -n currRow="Row$Line"     # make currRow an alias for that array
    for ((i=0; i<9; i++)); do         # perform our inner loop...
      currRow+=( "$i" )               # ...and populate the target array...
    done
    unset -n currRow                  # then clear the alias so it can be reassigned later.
  done
}

References:

Sign up to request clarification or add additional context in comments.

Comments

0

Variable expansion happens too late for an assignment to understand it. You can delay the assignment by using the declare builtin. -g is needed in a function to make the variable global.

Also, you probably don't want to use $Line as the array index, but $i, otherwise you wouldn't populate each line array with numbers 1..9.

#! /bin/bash
Row0=()
Row1=()
Row2=()

FillArrays() {
    for Line in $(seq 0 8)
    do
        for i in $(seq 1 9)
        do
            declare -g Row$Line[$i]=$i
        done
    done
}

FillArrays
echo "${Row1[@]}"

But note that using variables as parts of variable names is dangerous. For me, needing this always means I need to switch from the shell to a real programming language.

1 Comment

Have we established that the OP is using a shell too old to support namevars (being the modern/supported way to do indirect assignment)? Using declare -g already rules out a bunch of old shells, so I don't think there's that strong of a portability argument.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.