On 11/1/13, 12:37 AM, Peggy Russell wrote: > Hi, > > "declare -g var" should return a nonzero return code when it fails. > > Declaring a local variable as global in a function, has a exit status of 0, > but the operation was not successful (see test_error). "help declare" and > the bash man page indicate the exit status will indicate success or failure.
There is a problem here, and the problem that causes the spurious error message from test_error has been fixed in bash-4.3. However, I don't think you completely understand what bash scoping is, or what makes a variable set or unset. First, using declare without assigning a value creates a variable "placeholder". The variable exists as more-or-less invisible, but is not considered set until it is assigned a value. Therefore, declare -g var just creates a placeholder at the global scope if there is no existing global variable with that name. If there is such a variable, it's a no-op. The `redeclare local variable as global' comment is just incorrect. Second, declaring a variable, even a placeholder, at the global scope does nothing to a variable with the same name at the local scope. Bash's scoping rules mean that it will use a local variable instead of a global variable if there is a local variable declared in the currently-executing function. That's why the assignments of "data2" and "data3" affect the local variable and disappear when the function returns. > The "declare -g var", did not just fail with a return code of 0, but it > also removed the variable from the environment. Isn't that grounds for > a nonzero return code... That's a bug in bash-4.2. The correct output is test_success: rc [0] declare -- var="data1" == test_success: [data1] ./x2: line 27: declare: var: not found test_error: rc [0] declare -- var="data2" test_error: rc [0] declare -- var="data2" declare -- var="data3" == test_error: [] Chet -- ``The lyf so short, the craft so long to lerne.'' - Chaucer ``Ars longa, vita brevis'' - Hippocrates Chet Ramey, ITS, CWRU c...@case.edu http://cnswww.cns.cwru.edu/~chet/