Home > Blockchain >  When echoing $LINENO from a function, echo the line the function is being ran instead of the actual
When echoing $LINENO from a function, echo the line the function is being ran instead of the actual

Time:10-08

This is a follow-up to this post. Someone told me how to use a DEBUG trap to run a command before every line, and I made function that executes in the trap. But, when echoing $LINENO from a function, it echos the literal line number. I need the line number that the function is being ran in. How do I do this?

More explaining, say a function foo was defined at line 25 and is ran at line 100. foo has the command echo "$LINENO" at line 26. Instead of echoing 26 (Where foo is defined and the echo command is located), I want it to echo 100 (Where the function foo is being ran).

And I'm pretty sure you don't need my code, since I just need help with getting the line number that the function is being executed in. But, for the people who absolutely need to look at my code for some reason: You probably won't find anything useful in my code.

getnextp() {
  i=0
  small=$1
  execute=
  while :; do
    ((i  ))
    if [ "$i" -gt "$(sed -n '$=' plist)"]; then
      break
    fi
    line=$(sed $i'!d' plist)
    if [ "$line" == "$0" ]; then
      ((i  ))
      ((i  ))
      line=$(sed $i'!d' plist)
      if [ "$line" -lt "$small" ]; then
        small="$line"
        ((i--))
        line=$(sed $i'!d' plist)
        execute=$line
        ((i  ))
      fi
    fi
  done
}
npl=999999999
step() {
  echo "Working."
  echo $LINENO
  if [ "$(cat plist)" == *"$0"* ]; then
    getnextp $1
    if [ "$LINENO" == "$small" ]; then
      cd ../
      ./packages/$execute
    fi
  fi
}
trap "step $npl" DEBUG

CodePudding user response:

In bash, the array variable BASH_LINENO stores the trace. eg:

#!/bin/bash

foo() { 
    echo at $LINENO in foo, called from ${BASH_LINENO[0]}
    echo which was called from line ${BASH_LINENO[1]}; 
}
bar() { foo; }
bar
  • Related