3

I found this script:

#!/bin/bash

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

Over here: Bash Read Array from External File

I have a file called test.txt:

_127_0_0_1=kees

If I do in bash:

readvar ./test.txt _127_0_0_1

I get the output:

kees

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

#!/bin/ksh

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

readvar ./test.txt _127_0_0_1

I get the output:

$ ./test.sh

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

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

Community
  • 1
  • 1
azbc
  • 399
  • 1
  • 5
  • 12

1 Answers1

2

Here's 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 (an alias for typeset -n):

foo() {
  bar=42
  nameref indirect="$1"
  echo "$indirect"
}
foo bar
Henk Langeveld
  • 8,088
  • 1
  • 43
  • 57
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • 1
    `#!/bin/ksh foo() { while read -r line do typeset "$line" done < "$1" nameref indirect="$2" echo "$indirect" } foo ./test.txt _127_0_0_1` input test.txt: `_127_0_0_1=kees` output: `kees` – azbc Mar 25 '17 at 23:53
  • @azbc: Another convenient function of setting `nameref` in `ksh` is you can also change it's value (eg. `eval "${!indirect}=foobar"`) ... `echo "${!indirect}=${indirect}" ` – l'L'l Mar 25 '17 at 23:58