2017-03-25 29 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}」' –