执行Bash脚本时显示行号
Contents
1. 概述
当 Bash 脚本中发生错误时,准确了解错误发生的位置会很有帮助。在本教程中,我们将学习如何在调试 模式下执行 Bash 脚本时显示行号。
2.问题描述
首先,让我们编写一个帮助脚本,我们将在整个教程中使用它:
$ cat unity_comparison.sh
#! /bin/bash
read -p "Enter the input: " num1
if [ -z "$num1" ]
then
echo "The number is empty"
exit 0
fi
if [ "${num1}" -eq 1 ]
then
echo "Number entered is 1"
else
if [ "${num1}" -ge 1 ]
then
echo "Number entered is greater than one."
else
echo "Number entered is less than one."
fi
fi
此脚本测试用户输入的数字是等于 1、大于 1 还是小于 1。
让我们在调试模式下执行这个脚本:
$ bash -x ./unity_comparison.sh
+ read -p 'Enter the input: ' num1
Enter the input: 4
+ '[' -z 4 ']'
+ '[' 4 -eq 1 ']'
+ '[' 4 -ge 1 ']'
+ echo 'Number entered is greater than one.'
Number entered is greater than one.
正如我们所观察到的,输出看起来很混乱。此外,很难将调试输出与脚本中相应的行号关联起来。在下一节中,我们将研究解决此问题的方法。
3.解决方案
特殊的shell 变量 PS4 定义了当我们在xtrace模式下执行 shell 脚本时显示的提示。PS4的默认值为“ + ”:
$ echo $PS4
+
我们可以更改PS4变量的值以在调试提示中显示行号。为此,我们将使用另一个特殊的 shell 变量LINENO。
让我们使用export命令使PS4变量可用于当前 shell 的所有子进程:
$ export PS4='Line $LINENO: '
现在,让我们在xtrace模式下执行我们的脚本并验证输出:
$ bash -x ./unity_comparison.sh
Line 2: read -p 'Enter the input: ' num1
Enter the input: -13
Line 3: '[' -z -13 ']'
Line 8: '[' -13 -eq 1 ']'
Line 12: '[' -13 -ge 1 ']'
Line 16: echo 'Number entered is less than one.'
Number entered is less than one.
现在,输出更具可读性,我们可以在调试输出中打印行号。
值得注意的是,我们在这里导出了当前 shell 中的变量,以便它可用于 shell 脚本。或者,我们也可以在脚本本身中设置PS4变量的值。