2

for loop shell script syntax error: unexpected word (expecting "do")

#!/bin/sh PRO="a t d e k " for file in $PRO do #this will be line 6 echo $file done

output: line 6: syntax error: unexpected word (expecting "do")

  • 1
    You probably have DOS line endings in your file, so that the shell sees `do\r` instead of `do`. – chepner Apr 05 '17 at 12:14
  • How can i verify that ? – Rahul M Ashlesh Apr 06 '17 at 05:27
  • @chepner, yes .. found a ^M when i opened it in vi editor. It helped me to solve it. Later used the dos2unix command by referring to http://linuxcommand.org/man_pages/dos2unix1.html – Rahul M Ashlesh Apr 07 '17 at 06:22
  • Possible duplicate of [Are shell scripts sensitive to encoding and line endings?](http://stackoverflow.com/questions/39527571/are-shell-scripts-sensitive-to-encoding-and-line-endings) – tripleee Apr 07 '17 at 06:29
  • As an aside, why would you put the loop tokens in a string variable in this case? `for file in a t d e k; do` doesn't seem less legible or maintainable at all, and has the distinct advantage that you can have file names with metacharacters etc in them, too (just quote them properly, of course; which you cannot easily do if they have to be in a string). – tripleee Apr 07 '17 at 06:29
  • Also use proper quoting in `echo "$file"` inside the loop. – tripleee Apr 07 '17 at 06:31

1 Answers1

0

Found a ^M when i opened it in vi editor. It helped me to solve it.

so it was some thing like this when i opened it in vi editor

for file in $PRO
   do^M                           
       echo $file
   done^M

Later used the dos2unix command by referring to computerhope.com/unix/dos2unix.htm