Re: bash variable expansion moment

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]



On Sun, Nov 15, 2009 at 01:50:30PM -0500, ken wrote:
> The problem is that $LINENO is evaluated in the function definition, and
> not when called.  So I'm thinking to change "$LINENO" in the function

No it's not.  Variables are _not_ evaluated when the function is defined;
they're evaluated at execution.  otherwise simple things like

  y=1
  x()
  {
    echo $y
  }
  y=10
  x
would not work.

You can show this, simply, with "typeset -f"
eg
  x()
  {
    echo Line is $LINENO
  }
  typeset -f

The result is
  x ()
  {
      echo Line is $LINENO
  }

Note that the variable has _not_ been evaluated; it's still there in the
function definition.

Your problem is that LINENO is a special variable that changes value as
the program executes.

As per the manpage:
       LINENO Each  time this parameter is referenced, the shell substitutes a
              decimal number representing the current sequential  line  number
              (starting  with  1)  within a script or function.

it's clear that when you enter a function it is reset to 1.  Thus:
  function y
  {
    echo in y, LINENO=$LINENO
  }
  echo LINENO=$LINENO
  y
results in
  LINENO=5
  in y, LINENO=3
because the echo statement is on the third line of the function.

You can not use $LINENO inside a function and expect it to represent the
line where the function is called.

So, again, reading the manpage, you need to look at the array BASH_LINENO;
in particular BASH_LINENO[0] is the line number of the line that calls
your function.

So...
  function x
  {
    echo We were called from line ${BASH_LINENO[0]}
  }

  echo LINENO=$LINENO before the call
  x
  echo LINENO=$LINENO after the call
may result in
  LINENO=6 before the call
  We were called from line 7
  LINENO=8 after the call

Is this what you wanted to do?

-- 

rgds
Stephen
_______________________________________________
CentOS mailing list
CentOS@xxxxxxxxxx
http://lists.centos.org/mailman/listinfo/centos

[Index of Archives]     [CentOS]     [CentOS Announce]     [CentOS Development]     [CentOS ARM Devel]     [CentOS Docs]     [CentOS Virtualization]     [Carrier Grade Linux]     [Linux Media]     [Asterisk]     [DCCP]     [Netdev]     [Xorg]     [Linux USB]
  Powered by Linux