- 工信部備案號 滇ICP備05000110號-1
- 滇公安備案 滇53010302000111
- 增值電信業(yè)務(wù)經(jīng)營許可證 B1.B2-20181647、滇B1.B2-20190004
- 云南互聯(lián)網(wǎng)協(xié)會理事單位
- 安全聯(lián)盟認證網(wǎng)站身份V標記
- 域名注冊服務(wù)機構(gòu)許可:滇D3-20230001
- 代理域名注冊服務(wù)機構(gòu):新網(wǎng)數(shù)碼
-n
激活語法檢查模式。它會讓 shell 讀取所有的命令,但是不會執(zhí)行它們,它(shell)只會檢查語法。
一旦 shell 腳本中發(fā)現(xiàn)有錯誤,shell 會在終端中輸出錯誤,不然就不會顯示任何東西。
激活語法檢查的命令如下:
$ bash -n script.sh
因為腳本中的語法是正確的,上面的命令不會顯示任何東西。所以,讓我們嘗試刪除結(jié)束 for 循環(huán)的 done
來看下是否會顯示錯誤:
下面是修改過的含? bug 的批量將 png 圖片轉(zhuǎn)換成 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
保存文件,接著運行該腳本并執(zhí)行語法檢查:
$ bash -n script.sh
檢查 shell 腳本語?
從上面的輸出中,我們看到我們的腳本中有一個錯誤,for 循環(huán)缺少了一個結(jié)束的 done
關(guān)鍵字。shell 腳本從頭到尾檢查文件,一旦沒有找到它(done
),shell 會打印出一個語法錯誤:
script.sh: line 11: syntax error: unexpected end of file
我們可以同時結(jié)合 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
此外,我們可以用內(nèi)置的 set 命令來在腳本中啟用調(diào)試模式。
下面的例子中,我們只檢查腳本中的 for 循環(huán)語法。
#!/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
再一次保存并執(zhí)行腳本:
$ ./script.sh
售前咨詢
售后咨詢
備案咨詢
二維碼
TOP