bug-bash
[Top][All Lists]
Advanced

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

is there a way to see if a var is declared so we can safely assign to it


From: L. A. Walsh
Subject: is there a way to see if a var is declared so we can safely assign to it (and...)
Date: Sun, 21 Aug 2016 17:54:48 -0700
User-agent: Thunderbird

This is a sample, of what I want:

#!/bin/bash -u

assign_var () {
   #if declared var; then
       var=assigned
   #else printf warn about global definition...; fi
}

lvl1 () {
   declare var
   assign_var
   printf "lvl1 var=%s\n" "$var"
}

lvl1
printf "main var after lvl1=%s\n" "${var:-undef}"

declare var
assign_var
printf "main var after assign_var=%s\n" "${var:-undef}"

---output----
lvl1 var=assigned
main var after lvl1=undef
main var after assign_var=assigned

---
What I'd want is for "assign_var" to be able to tell if
"var" had been explicitly defined, or if it was going
to end up in "global" ...

Barring checking for "declaredness", what about checking
what level the var will end up at (global or some function,
"n" levels deep)?

Is this possible in bash?
I want "assign_var" to through an error if "var"
isn't already defined (presumably used with a passed
varname).  "-v" only checks if var is non-empty, but there
seems no way to check if defined (since defined, alone,
determines where result will end up).  Of course, ideally,
I'd want it to work in previous versions of bash, but
I don't see how.  Maybe a "-D varname" in the conditional
checks?





reply via email to

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