大多数原因是因为 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
# 转换为 Unix 换行
$ vim windows.sh
:set ff=unix
:wq
# 转换为 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 ...
# 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
由于需要在脚本中转换,使用方法三不管用,所以使用了这个方式
cat windows.sh |tr -d ' '| tr -d '\r'
————————————————
参考:https://blog.csdn.net/jlh21/article/details/117065241