0

I am trying to read a file if file exist in a folder. But when I use if-then-else statement to check file exists or not, this error will occur. syntax error: unexpected end of file

I wrote script in centos7. I have tried in many ways to fix this error such as, removing square brackets, adding spaces and removing semi-columns. Still i couldn't find any solution.

flag="0"
path="/home/abc/file.txt"
if [ -f $path ]; then
 flag="1"
 echo "file exists"
else
 echo "file could't find"
fi

I expect to print set flag as "1" if file exists and print "file could't find" if file doesn't exist.

Hisham U
  • 25
  • 8
  • Do you really have a newline character after the `fi`? Check with `od -cx yourscript`. – user1934428 Nov 01 '19 at 07:22
  • Does your script file have DOS/Windows-style line endings? See: [Are shell scripts sensitive to encoding and line endings?](https://stackoverflow.com/questions/39527571/are-shell-scripts-sensitive-to-encoding-and-line-endings) – Gordon Davisson Nov 01 '19 at 08:05
  • @user1934428 - "0000560 d ' t f i n d " \r \n f i \r \n 2764 2074 6966 646e 0d22 660a 0d69 000a 0000577" this is the final line when executing od -cx file.sh – Hisham U Nov 01 '19 at 08:12
  • @GordonDavisson - Thank you, It worked after running sed -i 's/\r$//' file.sh – Hisham U Nov 01 '19 at 08:15
  • Since `then\r` is not `then`, the parser reaches the end of the script while still waiting for the keyword `then`. It just assumed that `then\r`, `else\r`, and `fi\`r` were all additional commands for the condition. – chepner Nov 01 '19 at 14:29
  • 1
    By the way, this is the *first* thing the [tag wiki](https://stackoverflow.com/tags/bash/info) suggests you check before posting a question. – chepner Nov 01 '19 at 14:30

1 Answers1

0

Your script runs quite fine. Chances are you've some special characters. Install dos2unix using yum install dos2unix or any other way and then do /usr/bin/dos2unix /path/your_script.sh. Now run your script and see if it works.

Sandeep Kanabar
  • 1,264
  • 17
  • 33