使用GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
,
#! /bin/bash
set -u
exec {FD1}>tmp1.txt
declare -r FD1
echo "fd1: $FD1" # why does this work,
function f1() {
exec {FD2}>tmp2.txt
readonly FD2
echo "fd2: $FD2" # this work,
}
f1
function f2() {
exec {FD3}>tmp3.txt
echo "fd3: $FD3" # and even this work,
declare -r FD3
echo "fd3: $FD3" # when this complains: "FD3: unbound variable"?
}
f2
目标是使我的文件描述符只读
答案 0 :(得分:3)
我不认为这是一个错误。 exec
语句为全局范围内的参数FD3
分配值,而declare
语句创建 local 参数,影响全局:
在函数中使用时,`declare'使NAME成为本地的,就像`local'一样 命令。 `-g'选项可以抑制这种行为。
这是未定义的本地参数。您可以通过稍微不同的示例来看到这一点:
$ FD3=foo
$ f () { FD3=bar; declare -r FD3=baz; echo $FD3; }
$ f
baz # The value of the function-local parameter
$ echo $FD3
bar # The value of the global parameter set in f