bash - Why is a shell script giving syntax errors when the same code works elsewhere? -
this question has answer here:
i have simple shell script copied working script. works if copy-paste terminal:
if true true fi however, when run script bash myscript, various syntax errors if of keywords missing.
myscript: line 4: syntax error near unexpected token `fi', ifthenisn't there.myscript: line 6: syntax error: unexpected end of file, iffiisn't there.myscript: line 4: syntax error near unexpected token `$'\r'.. what?
why happen in particular script, not on command line or in script copied from?
tl;dr: script has windows style crlf line endings, aka \r\n.
convert unix style \n deleting carriage returns.
how check if script has carriage returns?
they're detectable ^m in output of cat -v yourscript:
$ cat -v myscript if true^m then^m true^m ... how remove them?
set editor save file unix line endings, aka "line terminators" or "end-of-line characters", , resave it.
you can remove them command line dos2unix yourscript or cat yourscript | tr -d '\r' > fixedscript.
why carriage returns cause syntax errors?
the carriage return character character bash. then not same then\r, bash doesn't recognize keyword , assumes it's command. keeps looking then , fails
if there happens trailing space after then, similar problem fi.
Comments
Post a Comment