Linux下Shell脚本的调试

本文涉及的产品
实时计算 Flink 版,5000CU*H 3个月
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
大数据开发治理平台 DataWorks,不限时长
简介: 这篇博文是对Debugging Shell Scripts in Linux的翻译,希望能帮助到在Linux下写Shell脚本的童鞋。大多数编程语言都有可用的调试工具,调试工具可用在执行程序或脚本的时候让你检查其内部是如何进行的。对于Shell脚本,我们没有任何可用的调试工具,唯一有的是通过命令行的标识(-n,-v和-x)来辅助我们调试脚本。

这篇博文是对Debugging Shell Scripts in Linux的翻译,希望能帮助到在Linux下写Shell脚本的童鞋。

大多数编程语言都有可用的调试工具,调试工具可用在执行程序或脚本的时候让你检查其内部是如何进行的。对于Shell脚本,我们没有任何可用的调试工具,唯一有的是通过命令行的标识(-n,-v和-x)来辅助我们调试脚本。

Disabling the Shell (-n option)
所谓的-n标识,是noexec的缩写,意为no execution。该标识使得Shell并不执行其中的脚本,而是仅仅检查语法错误。-n标识并不能确保Shell会执行其它任何检查,实际上它只会执行常规的语法检查。通过使用-n标识,Shell不执行脚本中的命令,所以你可以很安全地检查你的脚本中是否包含语法错误。

下面的例子给出了如何使用-n标识。
例如该脚本文件名称为debug_quotes.sh

#!/bin/bash
echo "USER=$USER
echo "HOME=$HOME"
echo "OSNAME=$OSNAME"

现在添加-n标识来运行该脚本:

$ sh -n debug_quotes
debug_quotes: 8: debug_quotes: Syntax error: Unterminated quoted string

从上面的输出可以看出有一个语法错误,缺少双引号。

Displaying the Scripts Commands ( -v option )
所谓的-v标识使得Shell可以在详细输出模式(verbose mode)下运行。实际中,使用该标识可以在执行某行代码之前输出改行代码。这对于我们查找脚本错误是非常有帮助的。

下面我们创建一个Shell脚本,名称为“listusers.sh”,内容如下:

linuxtechi@localhost:~$ cat listusers.sh

#!/bin/bash

cut -d : -f1,5,7 /etc/passwd | grep -v sbin | grep sh | sort > /tmp/users.txt
awk -F':' ' { printf ( "%-12s %-40s\n", $1, $2 ) } ' /tmp/users.txt

#Clean up the temporary file.
/bin/rm -f /tmp/users.txt

下面我们使用-v标识来执行这个脚本。

linuxtechi@localhost:~$ sh -v listusers.sh

#!/bin/bash

cut -d : -f1,5,7 /etc/passwd | grep -v sbin | grep sh | sort > /tmp/users.txt
awk -F':' ' { printf ( "%-12s %-40s\n", $1, $2 ) } ' /tmp/users.txt
guest-k9ghtA Guest,,,
guest-kqEkQ8 Guest,,,
guest-llnzfx Guest,,,
pradeep pradeep,,,
mail admin Mail Admin,,,

#Clean up the temporary file.
/bin/rm -f /tmp/users.txt

linuxtechi@localhost:~$

在上面的输出中,脚本的原本输出和命令混在了一起。但是,通过使用-v标识,在脚本运行过程中,起码你可以知道当前脚本的执行状态。

Combining the -n & -v Options
我们也可以将多个标识进行组合(-n和-v)。通过这种组合可以得到更多好处,因为我们在查看脚本输出的过程中同时也检查了语法错误。

让我们再来看前面讨论过的脚本文件“debug_quotes.sh”。

linuxtechi@localhost:~$ sh -nv debug_quotes.sh

#!/bin/bash
#shows an error.

echo "USER=$USER
echo "HOME=$HOME"
echo "OSNAME=$OSNAME"

debug_quotes: 8: debug_quotes: Syntax error: Unterminated quoted string

linuxtechi@localhost:~$

Tracing Script Execution ( -x option )
所谓的-x标识,是xtrace或者execution trace的缩写,

目录
相关文章
|
3天前
|
网络协议 算法 Linux
【Linux】深入探索:Linux网络调试、追踪与优化
【Linux】深入探索:Linux网络调试、追踪与优化
|
1天前
|
弹性计算 运维 Shell
使用shell 脚本打印图形3
【4月更文挑战第29天】
4 0
|
1天前
|
存储 弹性计算 运维
使用shell 脚本打印图形2
【4月更文挑战第29天】
4 0
|
1天前
|
弹性计算 运维 Shell
使用shell 脚本打印图形1
【4月更文挑战第29天】
5 0
|
1天前
|
存储 弹性计算 运维
调整虚拟机内存参数的shell 脚本
【4月更文挑战第29天】
6 0
|
1天前
|
弹性计算 运维 Shell
从shell脚本发送邮件
【4月更文挑战第29天】
9 0
|
1天前
|
弹性计算 运维 Shell
使用 shell 脚本打印图形
【4月更文挑战第29天】
7 1
|
1天前
|
存储 弹性计算 运维
调整虚拟机内存参数的 shell 脚本
【4月更文挑战第29天】
9 2
|
2天前
|
关系型数据库 MySQL Shell
备份 MySQL 的 shell 脚本(mysqldump版本)
【4月更文挑战第28天】
7 0
|
2天前
|
弹性计算 运维 Shell
每天解析一个shell脚本(82)
【4月更文挑战第28天】shell脚本解析及训练(82)
6 1

热门文章

最新文章