手机看片精品高清国产日韩,色先锋资源综合网,国产哺乳奶水91在线播放,乱伦小说亚洲色图欧洲电影

幫助中心 >  技術知識庫 >  云服務器 >  服務器教程 >  如何在 Shell 腳本中執行語法檢查調試模式

如何在 Shell 腳本中執行語法檢查調試模式

2017-01-19 15:43:49 10702

-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

Check Syntax in Shell Script

檢查 shell 腳本語?

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

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

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

$ bash -vn script.sh

Enable Verbose and Syntax Checking in Script

在腳本中同時啟用 verbose 檢查和語法檢查

另外,我們可以通過修改腳本的首行來啟用腳本檢查,如下面的例子:

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


提交成功!非常感謝您的反饋,我們會繼續努力做到更好!

這條文檔是否有幫助解決問題?

非常抱歉未能幫助到您。為了給您提供更好的服務,我們很需要您進一步的反饋信息:

在文檔使用中是否遇到以下問題: