/bin/bash^M: bad interpreter: No such file or directory

转发请注明出处:

  今天在环境上执行某个脚本试,报如下异常:

# ./scp-to-testbed.sh 
-bash: ./scp-to-testbed.sh: /bin/bash^M: bad interpreter: No such file or director

  -bash: ./show-log.sh: /bin/bash^M: bad interpreter: No such file or directory

  这个错误表明:

    1. 脚本文件 show-log.sh 使用了 Windows 换行符(CRLF,即 \r\n,而 Linux 只支持 Unix 换行符(LF,即 \n

    2. ^M 是 Windows 的 \r(回车符)在 Linux 下的显示方式,导致 Shell 无法正确解析脚本。

1.判断文件的换行符类型

方法 1:使用 cat -v 显示隐藏字符

cat -v show-log.sh

  查看之后如下所示,每一行后面都会有^M

cat -v scp-to-testbed.sh 
#!/bin/bash^M
^M
ts=`/bin/date "+%Y-%m-%d_%H-%M-%S"`^M
CURR_DIR=`pwd`^M
CPU_ARC=`uname -m`^M
^M
FILE_NAME=terra-kibana-7.17.25_${ts}.tgz^M
rm -rf ${FILE_NAME}^M
tar zcvf ${FILE_NAME} build deploy^M
^M
scp ${FILE_NAME} $arm_testbed:/ybxiang/terra-kibana-7.17.25^M

方法 2:使用 file 命令

file show-log.sh

Windows 换行符 会显示:

show-log.sh: Bourne-Again shell script, ASCII text executable, with CRLF line terminators

Unix 换行符 会显示:

show-log.sh: Bourne-Again shell script, ASCII text executable

方法 3:用 vim 查看

 用 vim 打开文件:
vim show-log.sh

输入命令:

:set ff?
  • 显示 fileformat=dos → Windows 换行符(CRLF)。

  • 显示 fileformat=unix → Unix 换行符(LF)。

 2.解决方法:

方法 1:使用 dos2unix 转换文件

dos2unix show-log.sh

然后重新运行:

./show-log.sh

如果系统没有 dos2unix,先安装:

apt install dos2unix   # Debian/Ubuntu
yum install dos2unix   # CentOS/RHEL

方法 2:使用 sed 删除 \r 字符

sed -i 's/\r$//' show-log.sh

 

 

 

posted @ 2025-03-26 15:34  香吧香  阅读(296)  评论(0)    收藏  举报