Sample Header Ad - 728x90

bash - how to remove a local variable (inside a function)

7 votes
1 answer
579 views
I've read what's listed in Bibliography regarding unset, declare, local and "Shell Functions". My version of Bash is
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)
var='outer'
declare -p var
unset var
declare -p var
function foo {
  echo \""I'm in"\"
  local var='inner'
  declare -p var
  unset var
  declare -p var
}
foo
(the strange quoting around I'm in is there just to preserve syntax highlithing in the following block quote.) This prints
declare -- var="outer"
bash: declare: var: not found
"I'm in"
declare -- var="inner"
declare -- var
There is a difference in unsetting a global variable and unsetting a local variable inside a function. In the former case, the variable is removed. In the latter, the variable stays declared (but unset). Is there a way to completely remove a local variable inside a function (before the function returns)? That is that the output would be
declare -- var="outer"
bash: declare: var: not found
"I'm in"
declare -- var="inner"
bash: declare: var: not found
That would be useful to test if a variable is non existing inside a function, like in
function foo {
  local var
  while
    declare -p var
  do
    echo "$var"
    ((var++))
    [[ "$var" -eq 4 ]] \
    && unset var
  done
}
This code loops indefinitely, printing
declare -- var="1"
1
declare -- var="2"
2
declare -- var="3"
3
declare -- var

declare -- var="1"
1
declare -- var="2"
2
declare -- var="3"
3
declare -- var
[omissis]
Is there anything wrong in checking if a variable exists using declare -p? The only mention I found in the Bash reference manual about the difference between unsetting a global variable and a local one is > If a variable at the current local scope is unset, it will remain so (appearing as unset) until it is reset in that scope or until the function returns. (ref. Bash reference manual - sec. "Shell Functions") where the word _appearing_ is the only clue. **Bibliography** + [Bash reference manual] sec. "4 Shell Builtin Commands" + [What does unset do?]
Asked by the_eraser (185 rep)
Dec 10, 2024, 02:09 PM
Last activity: Dec 10, 2024, 05:34 PM