一、Shell 脚本执行时报错syntax error: unexpected end of file
从另一台服务器上拷贝一个脚本 执行报错line 40 : syntax error: unexpected end of file
,但脚本在另一台服务器上执行正常。
首先检查脚本的格式:vi 2019.sh
、:set ff
得出fileformat=unix
如果格式为dos,要把格式改为unix::set ff=unix
或者 :set fileformat=unix
仔细检查发现 是由于脚本里 while 循环 do之后的done少复制了。
syntax error: unexpected end of file
错误一般都是没有结束标记造成的。
仔细检查脚本中
- if之后有没有fi
- for 循环 do之后有没有done
- while 循环 do之后有没有done
二、shell脚本执行时报错syntax error near unexpected token
用命令vi -b test.sh
打开shell脚本文件,发现每行脚本最后多了个^M
,这是由于脚本是在Windows上写的, 因为Windows是回车+换行来表示换行,因此在Linux下用Vi查看在Windows下写的代码,行尾后的“^M”符号,表示的是换行符。
解决方法:用vi
替换功将^M
都去掉:vi -b test.sh
命令模式下,一般按ESC键;然后按:
输入 %s/^M//g
按下Enter键 一键替换所有^M
备注:一般情况下 shell脚本不是十分长,我们在windows上写好以后,可以直接复制脚本内容 ,到Linux上新建一个 vi test.sh
按i
然后直接粘贴进去,一般不会存在格式问题。