I understand I could use $LINENO
while debugging bash script to print out line number.
#!/bin/bash
set -x
PS4='${LINENO}: '
echo "hello"
set +x
Prints out the following if I run the script
$ ./script.sh
+ PS4='${LINENO}: '
4: echo hello
hello
That looks great. I can clearly see that the echo
came from line 4.
But, if I source the script, the line number gets somehow duplicated.
$ source script.sh
33: PS4='${LINENO}: '
44: echo hello
hello
55: set +x
Not sure what I'm doing wrong, but obviously my script doesn't have line numbers up to 33, 44, 55. It just seems like the line numbers are wrong. Why would sourcing the sourcing the script give this strange output?
$PS4
is the one used to indicate the "levels" of the shown line ( If$PS4
currently starts with a+
, it will show 1+
for a line at the level of the current shell, 2++
for a subshell, 3+++
for a further deep level, etc). As you instead use'${LINENO}'
, it will "evaluate"$LINENO
each time intoPS4
and take the fist (=higher) digit of the currently shown $LINENO (for exemple if it displays the line 204, it will use "2") as the characer to indicate the depth. PS4="204" would apparently become: "2204"