shell脚本报错:-bash: xxx: /bin/bash^M: bad interpreter: No such file or directory

今天写了一个shell脚本,然后在执行的时候报错,脚本内容很简单,仅供测试:

Shell 代码   
  1. #!/bin/sh  
  2.   
  3. echo "test shell "  
具体报错信息如下:
Shell 代码   
  1. [root@localhost test]# ./test.sh   
  2. -bash: ./test.sh: /bin/bash^M: bad interpreter: No such file or directory  
主要原因是 test.sh 是我在 windows 下编辑然后上传到 linux 系统里执行的。 .sh 文件的格式为 dos 格式。而 linux 只能执行格式为 unix 格式的脚本。
 
我们可以通过 vi 编辑器来查看文件的 format 格式。步骤如下:
1. 首先用 vi 命令打开文件
Shell 代码   
  1. [root@localhost test]# vi test.sh   
2. vi 命令模式中使用 :set ff 命令
可以看到改文件的格式为 dos
3. 修改文件 format unix
方法一:使用 vi 修改文件 format
命令: set ff=unix
执行完后再通过 set ff 命令查看文件格式,结果如下:
方法二:直接使用 dos2unix 命令修改
Shell 代码   
  1. [root@localhost test]# dos2unix test.sh   
  2. dos2unix: converting file test.sh to UNIX format ...  
  修改完后再次执行 ./test.sh ,执行正确:
Shell 代码   
  1. [root@localhost test]# ./test.sh   
  2. test shell   
分类 shell 脚本

猜你喜欢

转载自blog.csdn.net/qq919694688/article/details/80912598