歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux綜合 >> 學習Linux >> 詳解整理shell語法檢查模式

詳解整理shell語法檢查模式

日期:2017/3/3 17:36:13   编辑:學習Linux

詳解整理shell語法檢查模式


熱度1 評論 187 www.BkJia.Com 網友分享於: 2017-02-10 07:02:10 浏覽數4989次

詳解整理shell語法檢查模式


詳解shell語法檢查模式詳解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語法檢查模式詳解shell語法檢查模式

在 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

詳解shell語法檢查模式詳解shell語法檢查模式

從上面的輸出中,我們看到我們的腳本中有一個錯誤,for 循環缺少了一個結束的 done 關鍵字。shell 腳本從頭到尾檢查文件,一旦沒有找到它(done),shell 會打印出一個語法錯誤:

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

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

$ bash -vn script.sh

詳解shell語法檢查模式詳解shell語法檢查模式

我們還可以通過修改腳本的首行來啟用腳本檢查

如下面的例子:

#!/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 ‎


http://www.bkjia.com/Linuxjc/1191941.html TechArticle

Copyright © Linux教程網 All Rights Reserved