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)

1
  • $ ksh --version version sh (AT&T Research) 93u 2011-02-08 Commented Mar 25, 2017 at 22:21

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

#!/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: Another convenient function of setting nameref in ksh is you can also change it's value (eg. eval "${!indirect}=foobar") ... echo "${!indirect}=${indirect}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.