启用 verbose 调试模式
在进入本指导的重点之前,让我们简要地探索下 verbose 模式。它可以用 -v 调试选项来启用,它会告诉 shell 在读取时显示每行。要展示这个如何工作,下面是一个示例脚本来批量将 PNG 图片转换成 JPG 格式。
将下面内容输入(或者复制粘贴)到一个文件中。
#!/bin/bash
#convert
for image in *.png; do
convert "$image" "${image%.png}.jpg"
echo "image $image converted to ${image%.png}.jpg"
done
exit 0
接着保存文件,并用下面的命令使脚本可执行:
$ chmod +x script.sh
我们可以执行脚本并显示它被 Shell 读取到的每一行:
$ bash -v script.sh
在 Shell 脚本中启用语法检查调试模式
使用 -n 激活语法检查模式
它会让 shell 读取所有的命令,但是不会执行它们,它(shell)只会检查语法。一旦 shell 脚本中发现有错误,shell 会在终端中输出错误,不然就不会显示任何东西。
激活语法检查的命令如下:
$ bash -n script.sh
因为脚本中的语法是正确的,上面的命令不会显示任何东西。所以,让我们尝试删除结束 for 循环的 done 来看下是否会显示错误:
下面是修改过的含有 bug 的批量将 png 图片转换成 jpg 格式的脚本。
#!/bin/bash
#script with a bug
#convert
for image in *.png; do
convert "$image" "${image%.png}.jpg"
echo "image $image converted to ${image%.png}.jpg"
exit 0
保存文件,接着运行该脚本并执行语法检查:
$ bash -n script.sh
从上面的输出中,我们看到我们的脚本中有一个错误,for 循环缺少了一个结束的 done 关键字。shell 脚本从头到尾检查文件,一旦没有找到它(done),shell 会打印出一个语法错误:
script.sh: line 11: syntax error: unexpected end of file
我们可以同时结合 verbose 模式和语法检查模式:
$ bash -vn script.sh
我们还可以通过修改脚本的首行来启用脚本检查
如下面的例子:
#!/bin/bash -n
#altering the first line of a script to enable syntax checking
#convert
for image in *.png; do
convert "$image" "${image%.png}.jpg"
echo "image $image converted to ${image%.png}.jpg"
exit 0
如上所示,保存文件并在运行中检查语法:
$ ./script.sh
script.sh: line 12: syntax error: unexpected end of file
此外,我们可以用内置的 set 命令来在脚本中启用调试模式。
下面的例子中,我们只检查脚本中的 for 循环语法。
#!/bin/bash
#using set shell built-in command to enable debugging
#convert
#enable debugging
set -n
for image in *.png; do
convert "$image" "${image%.png}.jpg"
echo "image $image converted to ${image%.png}.jpg"
#disable debugging
set +n
exit 0
再一次保存并执行脚本:
$ ./script.sh
总的来说,我们应该保证在执行 Shell 脚本之前先检查脚本语法以捕捉错误。
shell语法,检查模式
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
更新日志
- 腾讯音乐人《浪漫火焰(新势力计划合辑 Vol.11)[FLAC/分轨][147.45MB]
- 2024年,哪里还可以玩有趣的魔兽RPG?
- 类银河恶魔城动作游戏《灵魂熔解》已正式登陆Steam
- 国庆七天总票房破20亿!《志愿军》8亿票房超速领跑!
- 绝区零轰隆隆驶向日落任务攻略 怎么完成
- dnf手游浩瀚星海神秘武器介绍 沧海长风武器升级
- 初音未来缤纷舞台国服预约开启 上线时间一览
- s14全球总决赛瑞士轮抽签结果是什么 S14瑞士轮抽签结果详情
- gam是哪个国家的队 s14世界赛gam战队国家赛区介绍
- s14全球世界赛主题是什么 英雄联盟s14世界赛最新主题介绍
- 鉴宝博主半年涨粉1500万 鉴宝成网友新晋电子榨菜
- 重大里程碑!《底特律 化身为人》销量突破1000万套
- 网友总结游戏业界七宗罪厂商:暴食的微软 傲慢的育碧
- 棒棒堂.2007-哪里怕(引进版)【EMI百代】【WAV+CUE】
- 邓丽君.2024-美好世界8CD(日本唱片志限量编号版)【环球】【WAV+CUE】