bash 与 ksh 中的变量重定向
Variable Redirect in bash vs. ksh
我找到了这个脚本:
#!/bin/bash
readvar () {
while read -r line
do
declare "$line"
done < ""
echo ${!2}
}
这里:
Bash 从外部文件读取数组
我有一个名为 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 < ""
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=""
echo "$indirect"
}
foo bar
我找到了这个脚本:
#!/bin/bash
readvar () {
while read -r line
do
declare "$line"
done < ""
echo ${!2}
}
这里: Bash 从外部文件读取数组
我有一个名为 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 < ""
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=""
echo "$indirect"
}
foo bar