为什么一个shell脚本提供语法错误时同样code工作在别处? [英] Why is a shell script giving syntax errors when the same code works elsewhere?

查看:111
本文介绍了为什么一个shell脚本提供语法错误时同样code工作在别处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的shell脚本我从工作的脚本复制。它的工作原理,如果我把它复制粘贴到终端:

I have a simple shell script I copied from a working script. It works if I copy-paste it to a terminal:

if true
then
  true
fi 

然而,当我运行庆典的MyScript 剧本,我得到了各种各样的语法错误,如果某些关键字的丢失。

However, when I run the script with bash myscript, I get various syntax errors as if some of the keywords are missing.


  • 的MyScript:4号线:附近意外的标记'网络',语法错误,如果然后不存在

  • 的MyScript:6号线:语法错误:意外的文件结尾,仿佛网​​络是不存在的。

  • 的MyScript:4号线:附近意外的标记`$语法错误'\\ r' ..什么

  • myscript: line 4: syntax error near unexpected token `fi' , as if then isn't there.
  • myscript: line 6: syntax error: unexpected end of file , as if fi isn't there.
  • myscript: line 4: syntax error near unexpected token `$'\r' .. what?

这为什么会发生在这个特殊的脚本,但不是我的命令行或脚本,我从复制?

Why does this happen in this particular script, but not on my command line or in the script I copied from?

推荐答案

TL; DR:将脚本的Windows风格CRLF行结束,又名 \\ r \\ n

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

\\ n 通过删除回车转换为Unix风格。

Convert to Unix style \n by deleting the carriage returns.

他们可检测 ^ M 中的输出猫-v yourscript

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

如何删除?

设置你的编辑器来保存Unix行结尾的文件,又名行终止符或结束的行字符,并重新保存它。

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.

您可以在命令行中使用 DOS2UNIX的yourscript 猫也删除它们yourscript | TR -d'\\ r'> fixedscript

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

回车符只是另一个字符打坏。 然后是不一样的然后\\ r ,因此庆典不能识别它作为关键字,并假定它是一个命令。然后它保持在寻找一个然后和失败

The carriage return character is just another character to bash. then is not the same as then\r, 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.

这篇关于为什么一个shell脚本提供语法错误时同样code工作在别处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆