• CRLF line terminators导致shell脚本报错:command not found --转载


    Linux和Windows文本文件的行结束标志不同。在Linux中,文本文件用"/n"表示回车换行,而Windows用"/r/n"表示回车换行。有时候在Windows编写shell脚本时需要注意这个,否则shell脚本会报"No such file or directory"或"command not found line x"之类的错误,如果不知晓前因后果,肯定会被这个折腾得相当郁闷。如下所示test.sh

    [root@DB-Server myscript]# more test.sh 
    . /home/oracle/.bash_profile
    echo ' '
    date
    echo ' '
     
    sqlplus test/test @/home/oracle/scripts/test.sql
     
    echo ' '
    date
    echo ' '

    执行test.sh脚本过程中报" No such file or directory /home/oracle/.bash_profile" 和"command not found line xx". 如果你从shell脚本语法方面去检查,根本没有任何问题。不知具体原因的肯定相当郁闷。

    [oracle@DB-Server myscript]$ ./test.sh
     
    : No such file or directory /home/oracle/.bash_profile
     
    : command not found line 2: 
     
    : command not found line 4: date
     
    : command not found line 6: 
     
    : command not found line 7: 

    如果你用file命令查看test.sh,你会发现文件编码为ASCII,with CRLF line terminators。我们用cat -v test.sh 可以看到^M ( 的十六进制为0D,对应的控制符为^M)。 cat -v可以看到文件中的非打印字符。

    [root@DB-Server myscript]# 
    [root@DB-Server myscript]# file test.sh 
    test.sh: ASCII text, with CRLF line terminators
    [root@DB-Server myscript]# cat -v test.sh 
    . /home/oracle/.bash_profile^M
    echo ' '^M
    date^M
    echo ' '^M
    ^M
    sqlplus test/test @/home/oracle/scripts/test.sql^M
    ^M
    echo ' '^M
    date^M
    echo ' '^M
    [root@DB-Server myscript]# 

    clip_image001

    vi命令查看test.sh文件看不到^M, 其实这个跟vi的版本有关系。有些版本vi显示的是行尾为^M(AIX下都是显示^M)。而有些vi打开时可以看到底下有[dos]的格式提示。

    clip_image002

    我们可以用file命令对比正常的shell脚本的格式和编码。如下所示

    [oracle@DB-Server myscript]$ file myshell.sh
     
    myshell.sh: Bourne-Again shell script text executable

    解决这个问题其实也不难,有很多方式,例如直接使用vi编辑器编写shell脚本;使用cat命令创建shell脚本,然后从Windows文本工具里面拷贝脚本过来;最方便的还是使用dos2unix将DOS格式文本文件转换成Unix格式或Linux格式。

    clip_image003

    作者:潇湘隐者

    如果你真心觉得文章写得不错,而且对你有所帮助,那就不妨小小打赏一下吧,如果囊中羞涩,不妨帮忙“推荐"一下,您的“推荐”和”打赏“将是我最大的写作动力!

    本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接.
  • 相关阅读:
    隧道适配器,本地连接过多的解决办法
    C# 遍历HashTable
    sql2005 数据库转为sql 2000数据库的步骤
    自动扫描IP代理地址和自动切换IP的软件
    JS实现网页图片延迟加载[随滚动条渐显]
    批量修改hosts
    C#.NET获取当前月份最大天数
    如何让js调用不影响页面的加载速度?
    在sql中如何替换去掉回车符?
    Linq(01)对Linq的疑问及学习路径
  • 原文地址:https://www.cnblogs.com/nkwy2012/p/6297522.html
Copyright © 2020-2023  润新知