0

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?

1
  • Is the backslash after echo really there? If so, you should remove it because it escapes the linebreak. Commented Dec 8, 2017 at 14:34

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

the edit changed the code for incrementing i that I originally posted.

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.