bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Uxexpected complaint of "unbound variable"


From: Chet Ramey
Subject: Re: Uxexpected complaint of "unbound variable"
Date: Tue, 05 May 2015 08:55:48 -0400
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:31.0) Gecko/20100101 Thunderbird/31.6.0

On 5/4/15 9:03 PM, James Caccese wrote:
> I posted the following question to stackoverflow
> (http://stackoverflow.com/questions/30042157/why-cant-i-use-declare-r-inside-a-function-fo-mark-a-variable-readonly-while)
> and was advised the behavior I was witnessing was a bug in bash.

It's not a bug; it's an application of bash's scoping rules and the rules
about when a varible is not set.

> 
> 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,

You create a global variable and modify its attributes.

> 
> function f1() {
>   exec {FD2}>tmp2.txt
>   readonly FD2
>   echo "fd2: $FD2"     # this work,

You create a global variable and modify its attributes.

> }
> 
> f1
> 
> function f2() {
>   exec {FD3}>tmp3.txt
>   echo "fd3: $FD3"     # and even this work,

You create a global variable.

>   declare -r FD3

You create a `placeholder' local variable that has no value, shadowing the
global variable.  When you use `declare' or its synonym `typeset' inside a
shell function, you create local variables.

The variable has no value, since you haven't assigned it one, and so is
technically unset.

>   echo "fd3: $FD3"     # when this complains: "FD3: unbound variable"?

Scoping: the variable with that name in the closest scope is the (unset)
local copy of FD3.

-- 
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, ITS, CWRU    chet@case.edu    http://cnswww.cns.cwru.edu/~chet/



reply via email to

[Prev in Thread] Current Thread [Next in Thread]