解决 syntax error: unexpected end of file 或者 /bin/bash^M: bad interpreter: No such file or directory

我们在windows上创建shell脚本文件,上传到linux服务器,执行shell脚本时,不出意外的话,会报下面的错误:

syntax error: unexpected end of file 或者 /bin/bash^M: bad interpreter: No such file or directory

举例:

[root@sjk3 ~]# sh percona-xtraDB-cluster-install.sh 
percona-xtraDB-cluster-install.sh: line 25: syntax error: unexpected end of file

或者

[root@sjk3 ~]# ./percona-xtraDB-cluster-install.sh 
-bash: ./percona-xtraDB-cluster-install.sh: /bin/bash^M: bad interpreter: No such file or directory

在执行shell脚本时,提示这样的错误主要是由于shell脚本文件是dos格式,即每一行结尾以\r\n来标识,而unix格式的文件行尾则以\n来标识。

查看脚本文件时dos格式还是unix格式的几种办法:

方法1

vi filename 或 vim filename 打开文件,如果是dos格式,则底部会有提示 [dos]

如果是unix格式,则底部没提示

方法2

vi filename 或 vim filename 打开文件,执行  :set ff,回车。如果文件为dos格式则显示为fileformat=dos,如果是unix格式则显示为fileformat=unix   如图:

,回车

方法3

cat -A filename  从显示结果可以判断,dos格式的文件行尾为 ^M$   ,unix格式的文件行尾为 $

解决方案:

方法1 

vi filename 或 filename 打开文件,执行:set ff=unix  设置文件为unix,然后执行:wq,保存成unix格式 。

方法2

使用sed命令 sed -i "s/\r//" filename 或者 sed -i "s/^M//" filename 直接替换结尾符为unix格式。

猜你喜欢

转载自blog.csdn.net/wudinaniya/article/details/93419174
今日推荐