2

I am new to bash script and I wonder why I recieve the above message. I try to an arithmetic value which comes from the for loop and then I would like to print the array. Can anyone help me?

Thank you in advance!!

#!/bin/bash
declare -a SCORES
for j in `seq 0 5`;
do
SCORES$j="$(sh myscript.sh $DSLAM $j | grep "" -c )"
done
for k in "${SCORES[@]}"
do
    echo "message $'\t' $SCORES$k"
done
echo ${#SCORES}

=======

Output

abcd.sh: line 16: SCORES0=3: command not found
abcd.sh: line 16: SCORES1=135: command not found
abcd.sh: line 16: SCORES2=826: command not found
abcd.sh: line 16: SCORES3=107: command not found
abcd.sh: line 16: SCORES4=3: command not found
abcd.sh: line 16: SCORES5=3: command not found
0

1 Answer 1

4

You cannot assign variable with name, which is generated at run time; at least not the way you are trying.

You have below options:

declare "SCORES$j=$(sh myscript.sh $DSLAM $j | grep '' -c )" # creates new variables like SCORES1, SCORES2 etc.

eval "SCORES$j=$(sh myscript.sh $DSLAM $j | grep '' -c )" #Definitely not preferred.

SCORES[$j]="$(sh myscript.sh $DSLAM $j | grep '' -c )" #uses array you have created. 

Most likely, option 3 is what you want.

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

3 Comments

Using eval is only necessary in POSIX shell, which has neither arrays nor the declare command. You should not even consider using it for this purpose in bash.
^^ I agree.. @chepner: About the edit: Is it really required? I think, double quotes inside $() do not act as the closing double quotes for double quotes started at declare "... try declare "t=$(seq 1 20 | grep "2")"; echo "$t"
^^ mywiki.wooledge.org/BashFAQ/048 Or just google for "bash eval is evil" you would find more examples. In nutshelll, eval opens up the possibility of code injections. My bad... I should not have suggested the bad practice in first place.

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.