I understand I could use $LINENO while debugging bash script to print out line number.

set -x
PS4='${LINENO}: '
echo "hello"
set +x

Prints out the following if I run the script

$ ./script.sh
+ PS4='${LINENO}: '
4: echo 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
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?

2 Answers 2


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.


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.

  • 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
    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
    Feb 25, 2021 at 16:49
  • Ah, I see! Good point, thanks for the explanation.
    – AdminBee
    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 .