關於shell指令碼編輯出現亂碼的問題

2021-07-29 18:48:47 字數 2474 閱讀 1030

file命令檢視檔案屬性為*.sh ascii text, with crlf line terminators

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可以看到檔案中的非列印字元。

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格式。

Shell指令碼實現對檔案編輯

常見linux檔案的編輯命令 vi vim,有時候我們想寫乙個指令碼實現對檔案編輯,這個時候,可能就不夠用了,下面介紹一些辦法 1 echo命令 shell的echo命令常用於字串的輸出 例如 root mdw zxy echo hello world file1 root mdw zxy cat ...

windows編輯shell指令碼執行報錯

windows編輯shell指令碼執行報錯 問題 2019年10月,在開發需求的時候需要在主機上編寫shell指令碼。因為自己使用的是win系統,在notepad 編寫指令碼。將指令碼上傳主機後,執行報錯 syntax error near unexpected token do 將主機上可正常執行...

Shell指令碼實現對檔案編輯

常見linux檔案的編輯命令 vi vim,有時候我們想寫乙個指令碼實現對檔案編輯,這個時候,可能就不夠用了,下面介紹一些辦法 1 echo命令 shell的echo命令常用於字串的輸出 例如 root mdw zxy echo hello world file1 root mdw zxy cat ...