- 工信部備案號 滇ICP備05000110號-1
- 滇公安備案 滇53010302000111
- 增值電信業務經營許可證 B1.B2-20181647、滇B1.B2-20190004
- 云南互聯網協會理事單位
- 安全聯盟認證網站身份V標記
- 域名注冊服務機構許可:滇D3-20230001
- 代理域名注冊服務機構:新網數碼
-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 腳本語?
從上面的輸出中,我們看到我們的腳本中有一個錯誤,for 循環缺少了一個結束的 done
關鍵字。shell 腳本從頭到尾檢查文件,一旦沒有找到它(done
),shell 會打印出一個語法錯誤:
script.sh: line 11: syntax error: unexpected end of file
我們可以同時結合 verbose 模式和語法檢查模式:
$ bash -vn script.sh
在腳本中同時啟用 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
售前咨詢
售后咨詢
備案咨詢
二維碼
TOP