解决Linux环境下执行脚本时报错:/bin/bash^M: 坏的解释器: 没有那个文件或目录

一、问题描述

我在Windows 10 系统下编辑了一个发送消息到企业微信的shell脚本文件,然后copy到了远程的Linux服务器,当运行的时候报错了。如下所示:

未分类

root@ubuntu116:/data/gitlabData/auto_back_shell# ./qiyewechat-notifier.sh 
-bash: ./qiyewechat-notifier.sh: /bin/bash^M: 坏的解释器: 没有那个文件或目录
root@ubuntu116:/data/gitlabData/auto_back_shell# 

二、错误原因

这个文件在Windows 下编辑过,在Windows下每一行结尾是nr,而Linux下则是n,所以才会有 多出来的r。

三、修改错误

使用指令sed -i 's/r$//' xxxxxxx.sh,上面的指令会把 xxxxxxx.sh 中的r 替换成空白!
实操一下:

未分类

root@ubuntu116:/data/gitlabData/auto_back_shell# sed -i 's/r$//' qiyewechat-notifier.sh 
您在 /var/mail/root 中有新邮件
root@ubuntu116:/data/gitlabData/auto_back_shell# ./qiyewechat-notifier.sh -h 
./qiyewechat-notifier.sh: 非法选项 -- h
Usage:
  qiyewechat.sh [-u USER] [-t TITLE] [-c CONTENT] [-d DETAIL] [-p PICTURE]
Description:
    USER, 用户.
    TITLE, 标题.
    CONTENT, 内容.
    DETAIL, 细节.
    PICTURE, 图片.
root@ubuntu116:/data/gitlabData/auto_back_shell# 

如上所示,执行了下面的脚本之后,

sed -i 's/r$//' qiyewechat-notifier.sh

qiyewechat-notifier.sh就可以正常运行了!

四、附录

qiyewechat-notifier.sh的部分代码如下所示:

未分类

#!/bin/bash

#用法提示
usage() {
    echo "Usage:"
    echo "  qiyewechat.sh [-u USER] [-t TITLE] [-c CONTENT] [-d DETAIL] [-p PICTURE]"
    echo "Description:"
    echo "    USER, 用户."
    echo "    TITLE, 标题."
    echo "    CONTENT, 内容."
    echo "    DETAIL, 细节."
    echo "    PICTURE, 图片."
    exit -1
}


# 获取脚本执行时的选项
while getopts u:t:c:d:p: option
do
   case "${option}"  in
                u) USER=${OPTARG};;
                t) TITLE=${OPTARG};;
                c) CONTENT=${OPTARG};;
                d) DETAIL=${OPTARG};;
                p) PICTURE=${OPTARG};;
                h) usage;;
                ?) usage;;
   esac
   echo $option
   echo $OPTARG

done