gpt4 book ai didi

bash - bash 与 ksh 中的变量重定向

转载 作者:行者123 更新时间:2023-11-29 09:29:32 25 4
gpt4 key购买 nike

我找到了这个脚本:

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

最佳答案

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

关于bash - bash 与 ksh 中的变量重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43022454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com