詳解整理shell語法檢查模式

來源:互聯網
上載者:User

詳解整理shell語法檢查模式

啟用 verbose 偵錯模式

在進入本指導的重點之前,讓我們簡要地探索下verbose 模式。它可以用 -v 調試選項來啟用,它會告訴 shell 在讀取時顯示每行。要展示這個如何工作,下面是一個樣本指令碼來批量將 PNG 圖片轉換成 JPG 格式。

將下面內容輸入(或者複製粘貼)到一個檔案中。

#!/bin/bash#convertfor image in *.png; doconvert "$image" "${image%.png}.jpg"echo "image $image converted to ${image%.png}.jpg"doneexit 0

接著儲存檔案,並用下面的命令使指令碼可執行:

$ chmod +x script.sh

我們可以執行指令碼並顯示它被 Shell 讀取到的每一行:

$ bash -v script.sh

在 Shell 指令碼中啟用語法檢查偵錯模式使用 -n 啟用語法檢查模式

它會讓 shell 讀取所有的命令,但是不會執行它們,它(shell)只會檢查文法。一旦 shell 指令碼中發現有錯誤,shell 會在終端中輸出錯誤,不然就不會顯示任何東西。

啟用語法檢查的命令如下:

$ bash -n script.sh

因為指令碼中的文法是正確的,上面的命令不會顯示任何東西。所以,讓我們嘗試刪除結束 for 迴圈的 done 來看下是否會顯示錯誤:

下面是修改過的含有 bug 的批量將 png 圖片轉換成 jpg 格式的指令碼。

#!/bin/bash#script with a bug#convertfor image in *.png; doconvert  "$image"  "${image%.png}.jpg"echo "image $image converted to ${image%.png}.jpg"exit 0

儲存檔案,接著運行該指令碼並執行語法檢查:

$ bash -n script.sh

從上面的輸出中,我們看到我們的指令碼中有一個錯誤,for 迴圈缺少了一個結束的 done 關鍵字。shell 指令碼從頭到尾檢查檔案,一旦沒有找到它(done),shell 會列印出一個語法錯誤:

script.sh: line 11: syntax error: unexpected end of file

我們可以同時結合 verbose 模式和語法檢查模式:

$ bash -vn script.sh

我們還可以通過修改指令碼的首行來啟用指令碼檢查

如下面的例子:

#!/bin/bash -n#altering the first line of a script to enable syntax checking#convertfor image in *.png; doconvert  "$image"  "${image%.png}.jpg"echo "image $image converted to ${image%.png}.jpg"exit 0

如上所示,儲存檔案並在運行中檢查文法:

$ ./script.shscript.sh: line 12: syntax error: unexpected end of file

此外,我們可以用內建的 set 命令來在指令碼中啟用偵錯模式。

下面的例子中,我們只檢查指令碼中的 for 迴圈文法。

#!/bin/bash#using set shell built-in command to enable debugging#convert#enable debuggingset -nfor image in *.png; doconvert  "$image"  "${image%.png}.jpg"echo "image $image converted to ${image%.png}.jpg"#disable debuggingset +nexit 0

再一次儲存並執行指令碼:

$ ./script.sh

總的來說,我們應該保證在執行 Shell 指令碼之前先檢查指令碼文法以捕捉錯誤。

原文來自:https://linux.cn/article-8045-1.html

本文地址:http://www.linuxprobe.com/shellcheck-grammar.html ‎


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.