linux中调试脚本,在Linux下调试 Shell 脚本

在大多数编程语言中都有调试工具可用于调试。 调试工具可以运行需要调试的程序或脚本,使我们可以在运行时检查脚本或程序的内部执行过程。 在shell脚本中我们没有任何调试工具,只能借助命令行选项(-n,-v和-x)的帮助来进行调试。

禁用Shell(-n选项)

The -n option, shot for noexec ( as in no execution), tells the shell to not run the commands. Instead, the shell just checks for syntax errors. This option will not convince the shell to perform any more checks. Instead the shell just performs the normal syntax check. With -n option, the shell doesn’t execute your commands, so you have a safe way to test your scripts if they contain syntax error.

-n选项,为noexec缩写,告诉shell不运行命令。此时shell只检查语法错误。 使用此选项不会让shell执行任何更多检查。由于使用-n选项后,shell不会真的执行脚本中的命令,因此我们可以安全地测试脚本中包含的语法错误。

以下示例显示如何使用-n选项。

假设我们的Shell脚本名为debug_quotes.sh

#!/bin/bashecho "USER=$USERecho "HOME=$HOME"echo "OSNAME=$OSNAME"现在使用-n选项运行脚本$ sh -n debug_quotesdebug_quotes: 8: debug_quotes: Syntax error: Unterminated quoted string

上述输出显示存在语法错误,缺少双引号。

显示脚本命令(-v选项)

-v选项告诉shell以详细模式运行。 实际上,这意味着shell将在执行命令之前回显每个命令。 这非常有用,因为它通常可以帮助找到错误。

让我们创建一个名为“listusers.sh”的shell脚本,其中包含以下内容

lpicentral@localhost:~$ cat listusers.sh#!/bin/bashcut -d : -f1,5,7 /etc/passwd | grep -v sbin | grep sh | sort > /tmp/users.txtawk -F':' ' { printf ( "%-12s %-40s\n", $1, $2 ) } ' /tmp/users.txt#清理临时文件/bin/rm -f /tmp/users.txt现在使用-v选项执行脚本lpicentral@localhost:~$ sh -v listusers.sh#!/bin/bashcut -d : -f1,5,7 /etc/passwd | grep -v sbin | grep sh | sort > /tmp/users.txtawk -F':' ' { printf ( "%-12s %-40s\n", $1, $2 ) } ' /tmp/users.txtguest-k9ghtA Guest,,,guest-kqEkQ8 Guest,,,guest-llnzfx Guest,,,pradeep pradeep,,,mail admin Mail Admin,,,#清理临时文件/bin/rm -f /tmp/users.txtlpicentral@localhost:~$在上面的输出中,脚本输出与脚本的命令混合在一起。 但是,使用-v选项,至少可以更好地了解shell在运行脚本时所执行的操作。

结合使用 -n和-v选项

我们可以组合命令行选项(-n和-v)。 这是一个很好的组合,因为我们可以在看到脚本输出时检查脚本的语法。

让我们考虑以前使用过的脚本“debug_quotes.sh”lpicentral@localhost:~$ sh -nv debug_quotes.sh#!/bin/bash#shows an error.echo "USER=$USERecho "HOME=$HOME"echo "OSNAME=$OSNAME"debug_quotes: 8: debug_quotes: Syntax error: Unterminated quoted stringlpicentral@localhost:~$

跟踪脚本执行(-x选项)

-x选项是xtrace的缩写,它告诉shell在执行替换步骤后回显每个命令。 因此,我们可以看到变量和命令的值。 通常,仅此选项有助于诊断问题。

在大多数情况下,-x选项提供有关脚本的最有用信息,但它可能会导致大量输出。 以下示例显示了此选项的实际效果。

lpicentral@localhost:~$ sh -x listusers.sh+ cut -d :+ -f1,5,7 /etc/passwdgrep -v sbin+ sort+ grep sh+ awk -F: { printf ( "%-12s %-40s\n", $1, $2 ) } /tmp/users.txtguest-k9ghtA Guest,,,guest-kqEkQ8 Guest,,,guest-llnzfx Guest,,,pradeep pradeep,,,mail admin Mail Admin,,,+ /bin/rm -f /tmp/users.txtlpicentral@localhost:~$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值