Linux 执行 shell 报错 $‘\r‘ 的解决办法
原因
大多数原因是因为 shell 脚本是在 Windows
编写导致的换行问题,具体原因是 Windows
的换行符号为 CRLF(\r\n
),而 Unix\Linux
为 LF(\n)
。
名称解释
缩写 | 全称 | ASCII转义 | 说明 | |
---|---|---|---|---|
CR | Carriage Return | \r | 回车 | |
LF | Linefeed | \n | Unix\Linux 的换行符 | |
CRLF | Carriage Return & Linefeed | \r\n | 回车并换行,Windows 的换行符 |
查看
cat -A tmp.txt
修改
一、使用 vim
# 转换为 Unix 换行
$ vim windows.sh
:set ff=unix
:wq
二、dos2unix
# 转换为 Unix 换行
# 安装 dos2unix
$ yum install dos2unix
# 转换为 unix 格式
$ dos2unix windows.sh
dos2unix: converting file windows.sh to Unix format ...
# 转换为 dos 格式
$ unix2dos linux.sh
unix2dos: converting file linux.sh to DOS format ...
三、删除掉回车(\r)符号
# tr 删除 \r 回车符号,^M 终端输入为Ctrl+V和Ctrl+M
$ cat windows.sh | tr -d "^M" > windows2unix.sh
# sed 删除 \r 回车符号,^M 终端输入为Ctrl+V和Ctrl+M
$ sed -i "s/^M//g" windows.sh
四、tr 删除
由于需要在脚本中转换,使用方法三不管用,所以使用了这个方式
cat windows.sh |tr -d ' '| tr -d '\r'
————————————————
参考:https://blog.csdn.net/jlh21/article/details/117065241