Bash script: how can we use nested if in a for loop

#! /bin/bash count=1 step=(ab) for x in 0 1 do if [[ $count != '0' ]]; then if [[ ${step[x]} = "a"]]; then echo "Python test ($count)" else echo "stress test" fi fi done 

I get the following error

 syntax error in conditional expression: unexpected token `;' line 20: syntax error near `; line 20: ` if [[ ${step[x]} = "a"]]; then' 

Why?

+4
source share
2 answers

You need a space between "a" and ]] in the second if .

More technically, [[ and ]] should be separate tokens, and the bash parser does not split the tokens into quotes or large punctuation.

I believe your source code for the string is equivalent to if [[ ${step[x]} = "a]]"; then if [[ ${step[x]} = "a]]"; then if this makes the problem more obvious.

+5
source

Change

 if [[ ${step[x]} = "a"]]; then 

to

 if [[ ${step[$x]} = "a" ]]; then 

i.e. use $x instead of x and add a space after the last parameter.

Update: you do not need to enter the $ sign in the array indices before the variables (also in the double parenthesis (( )) or after the let keyword).

+1
source

Source: https://habr.com/ru/post/1338159/


All Articles