Ayan Dey
Ayan Dey

Reputation: 1

"syntax error near unexpected token `do'" in Bash script

I'm writing a Bash script. When I run it, I get a syntax error I don't understand.

Here my script:

#!/bin/bash
i=1
while [ $i -le "6" ]
 do
 j=1
 i=`expr $i +1`
 echo \
 while [ $j -le "$i" ]
   do
   echo $i
   j=`expr $j+1`
 done
done
echo \enter code here

Here the error:

./test.sh: line 9: syntax error near unexpected token `do'
./test.sh: line 9: `do'

What am I doing wrong?

Upvotes: 0

Views: 2647

Answers (1)

LHWizard
LHWizard

Reputation: 2389

The first thing if to remove the backslash from line 8, since it's an escape character (and it would escape the newline after it). In the final line, the backslash doesn't have that impact because it's followed by an e.

Also, in the expr expression, you need to surround the + sign with spaces. I also show a second way to increment j.

#!/bin/bash
i=1
while [ $i -le "6" ]
 do
 j=1
 ((i++))
 echo something-else
 while [ $j -le "$i" ]
   do
   echo $i
   ((j++))
 done
done

Output:

$ ./so_test.sh
something-else
2
2
something-else
3
3
3
something-else
4
4
4
4
something-else
5
5
5
5
5
something-else
6
6
6
6
6
6
something-else
7
7
7
7
7
7
7

Upvotes: 2

Related Questions