Syntax in a simple script

I am in the process of writing a script. A very preliminary version is giving a syntax error. The script is

#!/bin/bash
#file1='./data/heu/hout1'

exec 10<&0
exec < './data/heu/hout1'
#file1='./data/heu/hout1-
i=1
j=0
while read file1
do


	echo $file1
	echo $i
	if[$i==1] then
		arr1[$j]=file1
		$((i++))
	elif[$i==2] then
		arr1[$j]=file1
		$((i++))
	else
		$i=0
		$((j++))
	fi
done

The following errors get generated

line 21: syntax error near unexpected token `else'

Appreciate any inputs.

I noticed several syntax errors in your script.

  • If and elif conditional expressions missing blank spaces
  • Use -eq instead for numerical comparison
  • One can increment variable within (( )) without a $
  • Variable assignment $i=0 is incorrect. Remove the $
  • Array assignment missing $ sign before variable: file1

Here is the code with corrections:-

while read file1
do
        echo $file1
        echo $i
        if [ $i -eq 1 ]; then
                arr1[$j]="$file1"
                (( i++ ))
        elif [ $i -eq 2 ]; then
                arr1[$j]="$file1"
                (( i++ ))
        else
                i=0
                (( j++ ))
        fi
done

Many thanks for the detailed feedback. It will help me move forward. Is this code fine for reading the file?

exec 10<&0
exec < './data/heu/hout1'

The first line backs up &0 (=stdin) to &10.
The next line associates &0 with the file (the file is opened for reading).
Then all following stdin/default reading is from the file. Here it is the read command in the loop.
The reading from the file would stop if &0 were restored via exec 0<&10 .

Usually, instead of the exec association, you see a temporary association:

while read ...
do
...
done < './data/heu/hout1' 

After the "redirected" while-do-done block the original stdin is back.