【问题标题】:Variable Redirect in bash vs. kshbash 与 ksh 中的变量重定向
【发布时间】:2017-08-18 17:55:23
【问题描述】:

我找到了这个脚本:

#!/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

如果我在 bash 中这样做:

readvar ./test.txt _127_0_0_1

我得到了输出:

kees

但是,如果我在 ksh 中做同样的事情, (声明在 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)

【问题讨论】:

  • $ ksh --version version sh (AT&amp;T Research) 93u 2011-02-08

标签: bash variables reference ksh


【解决方案1】:

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

【讨论】:

  • #!/bin/ksh foo() { while read -r line do typeset "$line" done &lt; "$1" nameref indirect="$2" echo "$indirect" } foo ./test.txt _127_0_0_1 输入 test.txt:_127_0_0_1=kees 输出:kees
  • @azbc:在ksh 中设置nameref 的另一个方便的功能是您还可以更改它的值(例如eval "${!indirect}=foobar")...echo "${!indirect}=${indirect}"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 2020-04-04
  • 1970-01-01
  • 2011-12-15
  • 2019-02-09
  • 2017-12-31
相关资源
最近更新 更多