Why can't I use `declare -r` inside the fo function to denote a readonly variable while` set -u` is in use?
C 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
The goal is to make my file descriptor readonly
+3
source to share
1 answer
I don't think this is a mistake. The operator exec
assigns a value to a parameter FD3
in the global scope, and the operator declare
creates a local parameter that shadows the global one:
When used in a function, `declare 'makes the NAME local, as with the` local' command. The `-g 'option suppresses this behavior.
This is a local parameter undefined. You can see it a little differently:
$ 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
+3
source to share