0

Stupid example:

some_function()
{
  echo "here"
}

do_something ()
{
  local frame=0
  local values=()
  while values=($(caller $frame)); do
    local fline=${values[0]}
    local fname=${values[1]}
    local fsource=${values[2]}
    echo "Line ${fline} of '${fname}' in file ${fsource}."
    ((frame++))
  done

  echo "LINENO: $LINENO"
  echo "BASH_LINENO: ${BASH_LINENO[*]}"
  echo "FUNCNAME: ${FUNCNAME[*]}"
  echo "BASH_SOURCE: ${BASH_SOURCE[*]}"
  some_function
}

do_more ()
{
  # comment to change line numbering
  do_something
}

do_most ()
{
  do_more
}

If I call "do_most", I get output such as

Line 3 of 'do_more' in file test_lineno.sh.
Line 2 of 'do_most' in file test_lineno.sh.
LINENO: 12
BASH_LINENO: 3 2 200
FUNCNAME: do_something do_more do_most
BASH_SOURCE: test_lineno.sh test_lineno.sh test_lineno.sh
here

But what I want are the line numbers in the file, e.g., line 28 for 'do_more' or line 33 for 'do_most'. Is there a way to get that from bash?

Bash version: GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin21.6.0)

AdamC
  • 457
  • 1
  • 4
  • 14
  • 1
    You might have a look at https://wiki.bash-hackers.org/scripting/debuggingtips#making_xtrace_more_useful. See https://stackoverflow.com/questions/17804007/how-to-show-line-number-when-executing-bash-script – j_b Feb 15 '23 at 19:10
  • That could help in a particular instance, but I'm looking for a more general answer that could be scripted. I know about set -x, but it is not something I'd normally want turned on. – AdamC Feb 15 '23 at 19:19
  • 1
    If I run your script appending `do_most` at the last line, I get the correct (absolute) line numbers. My bash version is "5.0.17(1)-release". – Jardel Lucca Feb 15 '23 at 19:36
  • 1
    Aha! That's it. Apparently bash reports differently if I just source it vs. running it as a script. Probably points to more things about Bash I need to understand, but thank you! Might not help in my particular case (I'm sourcing a file in another script), but still some kind of progress. – AdamC Feb 15 '23 at 19:42

0 Answers0