bash与ksh中的变量重定向

3
我找到了这个脚本:
#!/bin/bash

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

在这里: Bash 从外部文件读取数组 我有一个名为test.txt的文件:
_127_0_0_1=kees

如果我在bash中执行以下操作:

readvar ./test.txt _127_0_0_1

我得到了输出:
kees

然而如果我在ksh中做同样的事情, (由于Declare在ksh中不起作用,因此我用typeset替换了它。) :

#!/bin/ksh

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

readvar ./test.txt _127_0_0_1

我得到了输出:
$ ./test.sh

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

为什么会这样?我该如何在ksh中使其工作?(特别是ksh93)

$ ksh --version version sh (AT&T Research) 93u 2011-02-08 - azbc
1个回答

2
这里是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.

如您所见,这与bash的操作完全不同。

对于ksh中的间接引用,您可以使用namereftypeset -n的别名):

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

1
`#!/bin/kshfoo() { 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=keesoutput:kees` - azbc
@azbc:在ksh中设置nameref的另一个方便之处是您还可以更改它的值(例如,eval "${!indirect}=foobar")... echo "${!indirect}=${indirect}" - l'L'l

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接