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]# 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM