Variable Forwarding in bash vs ksh

I found this script:

#!/bin/bash

readvar () {
    while read -r line
    do
            declare "$line"
    done < "$1"
    echo ${!2}
}

      

Here: Bash Reading an array from an external file

I have a test.txt file:

_127_0_0_1=kees

      

If I do in bash:

readvar ./test.txt _127_0_0_1

      

I am getting output:

kees

      

However, if I do the same in ksh, (Declare doesn't work in ksh, so I replaced it with a set.)

#!/bin/ksh

readvar () {
    while read -r line
    do
            typeset "$line"
    done < "$1"
    echo ${!2}
}

readvar ./test.txt _127_0_0_1

      

I am getting output:

$ ./test.sh

./test.sh: syntax error at line 8: `2' unexpected Segmentation fault: 11

      

Why? And how can I get it to work in ksh? (ksh93 for that matter)

+3


source to share


1 answer


Here man ksh

:

   ${!vname}
          Expands to the name of the variable referred to by vname.  
          This will be vname except when vname is a name reference.

      

As you can see, this is completely different from what bash does.



For indirection in, ksh

you can use nameref

(alias for typeset -n

):

foo() {
  bar=42
  nameref indirect="$1"
  echo "$indirect"
}
foo bar

      

+2


source







All Articles