zoukankan      html  css  js  c++  java
  • UnixLinux 执行 shell 报错:“$' ': 未找到命令” 的解决办法

    原因

    大多数原因是因为 shell 脚本是在 Windows 编写导致的换行问题,具体原因是 Windows 的换行符号为 CRLF ),而 UnixLinux 为 LF )。

    名称解释

    缩写 全称 ASCII转义 说明
    CR Carriage Return 回车
    LF Linefeed 换行,UnixLinux 的换行符
    CRLF Carriage Return & Linefeed 回车并换行,Windows 的换行符

    方法一(推荐):vim 转换为 Unix 换行

    # 测试脚本
    $ cat windows.sh
    #!/usr/bin/env bash
    date
    
    # 重现报错
    $ sh windows.sh
    windows.sh:行2: $'date
    ': 未找到命令
    
    # 查看文件格式信息
    $ file windows.sh
    windows.sh: a /usr/bin/env bash15 script, ASCII text executable, with CRLF line terminators
    
    # 转换为 Unix 换行
    $ vim windows.sh
    :set ff=unix
    :wq
    
    # 再次查看文件格式信息
    $ file windows.sh
    windows.sh: a /usr/bin/env bash script, ASCII text executable
    

    方法二:dos2unix

    # 安装 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 删除 
     回车符号,^M 终端输入为Ctrl+V和Ctrl+M
    $ cat windows.sh | tr -d "^M" > windows2unix.sh
    
    # sed 删除 
     回车符号,^M 终端输入为Ctrl+V和Ctrl+M
    $ sed -i "s/^M//g" windows.sh
    

    方法四:文本编辑器工具转换换行符合(如:atom、notepad++ 等)

    下图为 atom 编辑器的修改换行方式:

    作者:蒋李恒
    出处:https://www.cnblogs.com/daodaotest/
    如果你想及时得到个人撰写文章的消息推送,可以扫描左边二维码(或者长按识别二维码)关注个人微信公众号。
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    python文件句柄只能用一次的误解
    字符编码后续...记事本"联通"小插曲
    字符编码
    python problem
    vue-cli3 vue-config.js配置 概况
    ssh-keygen 不是内部或外部命令
    好的文章的链接收藏
    urlArgs 请require 缓存
    js 类型判断
    阻止冒泡和取消默认事件(默认行为)
  • 原文地址:https://www.cnblogs.com/daodaotest/p/14788697.html
Copyright © 2011-2022 走看看