I have a code like this:
#!/usr/bin/env bash
test_this(){
export ABC="ABC"
echo "some output"
}
final_output="the otput is $(test_this)"
echo "$ABC"
Unfortunately the variable ABC is not being set.
I have to call test_this like that, since in my real program I give some arguments to it, it performs various complicated operations calling various other functions, which on the way export this or that (basing on those arguments), and at the end some output string is assembled to be returned. Calling it two times, once to get exports and once for the output string would be bad.
The question is: what can I do to have both the exports and the output string in place, but just by one call to such a function?
The answer that I am happy with (thank you paxdiablo):
#!/usr/bin/env bash
test_this(){
export ABC="ABC"
export A_VERY_OBSCURE_NAME="some output"
}
test_this
final_output="the otput is $A_VERY_OBSCURE_NAME"
echo "$ABC" #works!
unset A_VERY_OBSCURE_NAME
Yes, it is being set. Unfortunately it’s being set in the sub-process that is created by
$()to run thetest_thisfunction and has no effect on the parent process.And calling it twice is probably the easiest way to do it, something like (using a “secret” parameter value to dictate behaviour if it needs to be different):
which outputs:
If you really only want to call it once, you could do something like:
In other words, use the same method for extracting output as you did for the other information.