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 (\r的十六進制為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]#vi命令查看test.sh文件看不到^M, 其實這個跟vi的版本有關系。有些版本vi顯示的是行尾為^M(AIX下都是顯示^M)。而有些vi打開時可以看到底下有[dos]的格式提示。
我們可以用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格式。
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的CRLF line terminators导致shell脚本报错:command not found的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 文件和byte数组转换
- 下一篇: Python快速学习06:词典