Shell script syntax error: unexpected end of line

advertisements

I wrote a simple shell script to check for the existence of a xml file and if it exists, then rename an old xml file to be backup and then move the new xml file to where the old xml file was stored.

#!/bin/sh    

oldFile="/Documents/sampleFolder/sampleFile.xml"
newFile="/Documents/sampleFile.xml"
backupFileName="/Documents/sampleFolder/sampleFile2.backup"
oldFileLocation="/Documents/sampleFolder"

if [ -f "$newFile" ] ; then
    echo "File found"
    #Rename old file
    mv $oldFile $backupFileName
    #move new file to old file's location
    mv $newFile $oldFileLocation
else
    echo "File not found, do nothing"
fi

However, every time I try to run the script, I get 4 command not found messages and a syntax error: unexpected end of file. Any suggestions on why I get these command not found errors or the unexpected end of file? I double checked that I closed all my double quotes, I have code highlight :)

EDIT: output from running script:

: command not found:
: command not found:
: command not found1:
: command not found6:
replaceXML.sh: line 26: syntax error: unexpected end of file


I believe you're running on Cygwin. There's more to the error messages than what you're seeing:

: command not found:
: command not found:
: command not found1:
: command not found6:
replaceXML.sh: line 26: syntax error: unexpected end of file

You probably used a Windows editor to create the script file, which means it uses Windows-style CR-LF ("\r\n") line endings, rather than Unix-style LF ('\n') line endings. Some programs under Cygwin can handle either form, but the shell doesn't.

For example, the line that looks like

then

looks to the shell like

then^M

where ^M is the ASCII CR character. This would actually be a valid command name if it existed, but it doesn't, so the shell complains:

then^M: command not found

But printing the CR character causes the cursor to go back to the beginning of the line, so everthing before the : is overwritten.

You're getting the "unexpected end of file" message because the shell never saw a fi to match the if.

You can use the dos2unix command to fix the line endings. Be sure to read the man page (man dos2unix); unlike most text filters, dos2unix replaces its input file rather than writing to stdout.