0.前言

通常我們在編輯 Linux 伺服器上的檔案時,直接在 Linux 環境比較麻煩(當然熟練使用 VIM 的程式設計師除外哈哈),有時我們會使用 Windows 將檔案編輯好再上傳到伺服器端,我用的是 Sublime text 。

1.問題描述與記錄

編輯完指令碼上傳到伺服器執行時,會出現語法錯誤,以下面的一小段指令碼為例

#!/bin/bash
echo "updatedb..."
sudo updatedb BASE_PATH=$(dirname $(locate $0))
echo ${BASE_PATH} if [ $BASE_PATH == "TODO" ]
then
echo "please modify this script with the base path of your bundler installation";
exit;
fi EXTRACT_FOCAL=${BASE_PATH}/bin/extract_focal.pl
echo ${EXTRACT_FOCAL} echo "[- Done -]"
cv@cv: ~/bundler$ bash runbundler.sh
runbundler.sh: line 4: $'\r': command not found
runbundler.sh: line 7: $'\r': command not found
runbundler.sh: line 13: $'\r': command not found
runbundler.sh: line 16: $'\r': command not found
runbundler.sh: line 17: syntax error: unexpected end of file

2. 問題分析與解決

這裡顯示的兩個問題都是因為我們的.sh檔案為dos格式,在 dos/windows 系統中按一次回車鍵實際上輸入的是CRLF ,即回車+換行。

而 Linux 系統一般只能執行 unix 格式的指令碼,在 Linux/Unix 系統中按一次回車鍵實際上輸入的是 LF ,即只有換行。

所以這裡在 Windows 系統編輯的 sh 指令碼檔案每行都多了一個回車,當在 Linux 系統中執行時就會報錯提示找不到相關命令。

我們可以檢視該指令碼的格式,在命令列使用 vim 開啟指令碼, ESC 進入命令輸入模式。

輸入 :set ff ,檢視輸出結果,比如我得到的是 fileformat=dos

此時我們可以使用:set ff=unix將 dos 格式更改為 unix 格式。

fffileformat的縮寫,因此也可以輸入 :set fileformat=unix

這時 :set ff 檢視會得到修改後的結果 fileformat=unix

然後再執行指令碼就不會出現上面的錯誤了!

(全文完)