-n
激活語(yǔ)法檢查模式。它會(huì)讓 shell 讀取所有的命令,但是不會(huì)執(zhí)行它們,它(shell)只會(huì)檢查語(yǔ)法。
一旦 shell 腳本中發(fā)現(xiàn)有錯(cuò)誤,shell 會(huì)在終端中輸出錯(cuò)誤,不然就不會(huì)顯示任何東西。
激活語(yǔ)法檢查的命令如下:
$ bash -n script.sh
因?yàn)槟_本中的語(yǔ)法是正確的,上面的命令不會(huì)顯示任何東西。所以,讓我們嘗試刪除結(jié)束 for 循環(huán)的 done
來(lái)看下是否會(huì)顯示錯(cuò)誤:
下面是修改過(guò)的含? 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
保存文件,接著運(yùn)行該腳本并執(zhí)行語(yǔ)法檢查:
$ bash -n script.sh

檢查 shell 腳本語(yǔ)?
從上面的輸出中,我們看到我們的腳本中有一個(gè)錯(cuò)誤,for 循環(huán)缺少了一個(gè)結(jié)束的 done
關(guān)鍵字。shell 腳本從頭到尾檢查文件,一旦沒(méi)有找到它(done
),shell 會(huì)打印出一個(gè)語(yǔ)法錯(cuò)誤:
script.sh: line 11: syntax error: unexpected end of file
我們可以同時(shí)結(jié)合 verbose 模式和語(yǔ)法檢查模式:
$ bash -vn script.sh

在腳本中同時(shí)啟用 verbose 檢查和語(yǔ)法檢查
另外,我們可以通過(guò)修改腳本的首行來(lái)啟用腳本檢查,如下面的例子:
#!/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
如上所示,保存文件并在運(yùn)行中檢查語(yǔ)法:
$ ./script.shscript.sh: line 12: syntax error: unexpected end of file
此外,我們可以用內(nèi)置的 set 命令來(lái)在腳本中啟用調(diào)試模式。
下面的例子中,我們只檢查腳本中的 for 循環(huán)語(yǔ)法。
#!/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