Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

bash - Why is a shell script giving syntax errors when the same code works elsewhere?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

TL;DR: Your script has Windows style CRLF line endings, aka .

Convert to Unix style by deleting the carriage returns.


How do I check if my script has carriage returns?

They're detectable as ^M in the output of cat -v yourscript:

$ cat -v myscript
if true^M
then^M
  true^M
...

How do I remove them?

Set your editor to save the file with Unix line endings, aka "line terminators" or "end-of-line characters", and resave it.

You can also remove them from a command line with dos2unix yourscript or cat yourscript | tr -d ' ' > fixedscript.

Why do carriage returns cause syntax errors?

The carriage return character is just another character to bash. then is not the same as then , so bash doesn't recognize it as a keyword and assumes it's a command. It then keeps looking for a then and fails

If there happens to be a trailing space after then, you get a similar problem for fi.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...