3

With 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

6
  • This reads as clearly a bug. Tried reporting it to the [email protected] list? May 5, 2015 at 0:16
  • exec {FD1}>tmp1.txt is new to me, what does that mean? I can't find that syntax in the manual section on redirection.
    – Barmar
    May 5, 2015 at 0:22
  • From gnu.org/software/bash/manual/html_node/Redirections.html, 2nd paragraph: Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}. In this case ... the shell will allocate a file descriptor greater than 10 and assign it to {varname} May 5, 2015 at 0:32
  • @CharlesDuffy I usually assume it's my lack of understanding, especially with bash. If I can't resolve it here, I certainly will try the bash-bugs email May 5, 2015 at 0:34
  • No, its not a bug, declare used inside a function indicates local scope
    – cdarke
    May 5, 2015 at 6:52

1 Answer 1

3

I don't think it's a bug. The exec statement assigns a value to the parameter FD3 in the global scope, while the declare statement creates a local parameter that shadows the global:

When used in a function, `declare' makes NAMEs local, as with the `local' command. The `-g' option suppresses this behavior.

It's the local parameter that is undefined. You can see this with a slightly different example:

$ 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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.