I wanted to try this approach in bash and it seems there is no straightforward way to do so. Example of what I was messing with:
Var1=foo
Var2=bar
Var3=
Var3 is deliberately left undefined in my tests with this.
After those variables, I use something ideally like this:
declare -a array=(Var1 Var2 Var3)
for array_element in ${array[@]};
do
if [[ $array_element ]];
then
echo "Element $array_element has content - true";
echo "The value of $array_element is foo."
echo
else
echo "Element $array_element has no content - false";
echo
fi
done
The desired end result I'm after to see if I can do it would be that if you had 3 or 30 possible variables, it would tell you if an array element has content or not, and then output that specific variable content. In this case, "foo" and "bar".
- Define a variable
- Define an array that includes the name of the variable only
- Check to see if the defined array has content (not if it's set--just is it blank or not)
- Then output the actual originally defined value of the array element.
Dynamic arrays, sort of? A basic bunch of
if [[ $Var1 ]]
if [[ $Var2 ]]
if [[ $Var3 ]]
works fine, but I want to wrap it up into something like this if I can to have less repetition of code. The long goal would be to have the variable be read, spit out whatever is defined as variables in a separate config file, and then fire off various functions defined elsewhere against that dynamic content. So, if this can be made to work, where I have up above:
echo "The value of $array_element is foo."
Would be replaced with a bunch of various functions() that would use foo as $1, essentially. But this part got me hitched up. My test above (unsurprisingly) fails as expected with all True hits, because it's just affirming $array_element is indeed set from the reading of the $array. I'm stuck on how to get the content that's defined up top under the $array_element. If you toss an "echo $Var1" anywhere in the file, it also outputs the expected "foo" regardless of where it is.
Can you do this in bash? I don't think I've seen variables used this way before and I'm not sure if I'm stuck on some mechanical problem/bash limitation or a logic problem in looking at it. I've been mucking around with it and a couple of approaches for a while with no luck, and Google and Stack Overflow searches have come up dry. Thanks for any help.