2

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?

1
  • The first char of $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 into PS4 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" Commented Sep 11 at 11:57

2 Answers 2

5

From man bash (emphasis mine):

PS4    The value of this parameter is expanded  as  with  PS1  and  the
value  is  printed  before  each command bash displays during an
execution trace.  The first character of PS4 is replicated  mul‐
tiple  times, as necessary, to indicate multiple levels of indi‐
rection.  The default is ``+ ''.

I'd suggest using PS4='+${LINENO}: ' instead, to preserve the default +, ++ ... indirection indication.

0

When you source a script, it acts as though the contents of the script are being entered by hand on the command line. Subsequent sourceing of the script would give higher "line numbers" as that metric effectively becomes an indicator for the number of commands executed in that shell session. This can be revealed by simply executing a printf "%s\n" "$LINENO" at an interactive prompt.

3
  • 2
    While that is true, shouldn't the line numbers still be numbered consecutively, e.g. 33, 34, 35 instead of 33, 44, 55?
    – AdminBee
    Commented Feb 25, 2021 at 16:44
  • 1
    They are sequential; it's just that what would be ++ is being shown as the line number twice due to deeper indireciton.
    – DopeGhoti
    Commented Feb 25, 2021 at 16:49
  • Ah, I see! Good point, thanks for the explanation.
    – AdminBee
    Commented Feb 25, 2021 at 16:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .