[CentOS] bash variable expansion moment

Sun Nov 15 13:54:55 UTC 2009
Stephen Harris <lists at spuddy.org>

On Sun, Nov 15, 2009 at 08:23:59AM -0500, ken wrote:
> A function containing environmental variables in one file would be
> called in another file.  The function would, then, pass (e.g.) $LINENO
> as if it were a literal, but in the line where $Line is invoked it would
> be evaluated and the value output.

I'm not quite sure what you're saying.  Typically variables are not expanded
at 'parse' time, but at run time.

eg

  x=1

  function foo
  {
    echo $x
  }

  x=100
  foo

You can see that "$x" is not expanded when it's first met (in the definition
of foo) but when foo is run.

$LINENO is a special internal variable that points to the current running
line, and so will change.  It's not being evaluated when the function
is compiled, but when you _run_ the function $LINENO will point to the
line inside the function.  That's what it is there for.  Do not use this
variable inside your program for anything other than debugging purposes.

Are you trying to do something like this?

  function bar
  {
    typeset var=$1
    eval typeset val='$'$var
    echo "$var=$val"
  }

  x=10
  y=100
  bar x
  bar y

Output of this is
  x=10
  y=100


Or are you trying to do debugging like this:

  trap 'echo At line $LINENO, x=$x' DEBUG
  x=10
  x=20
  echo Some output
  x=30
  trap '' DEBUG   # Stop tracking what X is set to
  x=40
  x=50

Here you'll see the DEBUG trap is called just before the command is executed
so you'll see things like
  At line 2, x=
  At line 3, x=10
  At line 4, x=20
  Some output
  At line 5, x=20
  At line 6, x=30

-- 

rgds
Stephen