一、问题情景:
最近在做开发时,在本地(Windows环境)Notepad里写好代码,直接上传到测试环境(Linux)运行出现了各种报错。原因是在本地用Notepad编写时,默认为windows格式,需要进行Unix格式的转换。(主要原因是Windows默认换行符为'\r\n',而Linux换行符为'\n')
二、产生的各种报错:
1. 找不到正确的 .bash_profile 路径
bash: ~/.bash_profile: No such file or directory
bash: ~/.bash_profile: No such file or directory
2. 换行符问题
line 2: $‘\r‘: command not found
line 2: $‘\r‘: command not found
3. 一些奇怪的字符问题,如
syntax error near unexpected token
syntax error near unexpected token `else'
三、解决方案:
方法一:直接在Notepad编辑器修改
在Notepad中选择:编辑——文档格式转换——转为Unix,之后再上传。
方法二:通过 dos2unix 指令
在执行脚本界面输入
dos2unix + 文件名
如:dos2unix my.rc
如果环境中没有安装dos2unix,可自行安装或用其他方法
## 安装dos2unix
yum install dos2unix
方法三:查找替换法
该方法只能解决部分问题。如这次遇到的三个问题,该方法只能解决1和2。
sed -i 's/\r//' 文件名
如:sed -i 's/\r//' my.rc
四、一些其他收获:
~./.bash_profile 是个隐藏文件。可通过 cat ~/.bash_profile 查看,来判断问题一不是因为这个文件被删了。