1

I am trying to execute this simple bash script but I am getting a syntax error. I followed this simple documentation here https://www.cyberciti.biz/faq/bash-for-loop/ but no luck. I am not sure what am I doing wrong?

#!/bin/bash
for i in 1 2 3 4 5
do
    echo "Count $i"
done;

error:

setup.sh: 3: setup.sh: Syntax error: word unexpected (expecting "do")

I am executing that script from my Windows Subsystem Linux (WSL) here.

  • 1
    for i in "1 2 3 4 5" – Kiwy Apr 26 '18 at 13:01
  • @Kiwy That would make for a boring loop ;-) – Kusalananda Apr 26 '18 at 13:15
  • I hate when bash decides to troll me like that... but still according to the explanation of the OP it could be correct – Kiwy Apr 26 '18 at 13:19
8

Your script file is a DOS text file. The extra carriage returns at the end of each line confuses bash (it sees do\r rather than do).

Convert it to a Unix text file using a tool such as dos2unix, or make sure that your editor saves it as a Unix text file.

  • That worked thank you. The problem is caused by my editor which is in windows. I thought WSL will handle the conversion by default. – Aftab Naveed Apr 26 '18 at 13:23
  • 1
    @AftabNaveed It's up to the editor to save the file correctly. The shell does no further modifications to the file's content (or there may be errors, for example if you really need a \r at the end of some line). – Kusalananda Apr 26 '18 at 13:25
0

I just executed same script in my centos machine which works file. As suggested by Kusalananda, convert the script file from dos to unix. install dos2unix package if you do not have it installed already. Then you can use below command to convert $dos2unix (name of the file)

0
#!/bin/bash
for i in 1 2 3 4 5
do
    echo "Count $i"
done;

A better way to loop would be:

for i in {1..5}; do
    echo "Count $i";
done

This way you do not have to specify all of those numbers. So what would you do if you had to loop through 100 numbers using your method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.