2017-03-25 28 views
3

我发现这个脚本:可变重定向在bash与ksh的

#!/bin/bash 

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

在这里: Bash Read Array from External File

我有一个名为test.txt文件:

_127_0_0_1=kees 

如果我这样做in bash:

readvar ./test.txt _127_0_0_1 

我得到的输出:(声明在ksh中不工作,所以我用排版取代它)

kees 

但是如果我做同样的事情在ksh中, :

#!/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的为此事)

+0

'$ KSH --version 版本SH(AT&T研究所)93u 2011-02-08' – azbc

回答

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,你可以使用nameref(别名为typeset -n):

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

'#!/bin中/ KSH FOO(){ 而读-r线 做 排版 “$线” 完成< “$ 1” nameref间接= “$ 2” 回声 “$间接” } foo ./test.txt _127_0_0_1'输入test.txt:'_127_0_0_1 = kees'输出:'kees' – azbc

+0

@azbc:另外一个方便的设置'ksh'中的'nameref'的功能是你也可以改变它的值(例如。 'eval“$ {!indirect} = foobar”')...''echo“$ {!indirect} = $ {indirect}”' –