Export does not work (from a function called to get its echo)

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 not set.

I need to call test_this , like this, because in my real program I give it several arguments, it performs various complex operations that call various other functions that are on the way to export this or that (based on these arguments) and at the end some then the output string to return. A call twice, once to get the export, and once for the output string will be bad.

Question: what can I do to have both export and output string, but only with one call to such a function?

The answer I'm happy with (thanks to 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 
+8
function bash export echo
source share
1 answer

Yes, it is installed. Unfortunately, it is installed in a subprocess that $() creates to run the test_this function and does not affect the parent process.

And calling it twice is probably the easiest way to do this, something like (using the value of the "secret" parameter to dictate behavior if it should be different):

 #!/usr/bin/env bash test_this(){ export ABC="ABC" if [[ "$1" != "super_sekrit_sauce" ]] ; then echo "some output" fi } final_output="the output is $(test_this)" echo "1:$ABC:$final_output" test_this super_sekrit_sauce echo "2:$ABC:$final_output" 

which outputs:

 1::the output is some output 2:ABC:the output is some output 

If you really want to call it only once, you can do something like:

 #!/usr/bin/env bash test_this(){ export ABC="ABC" export OUTPUT="some output" } test_this final_output="the output is ${OUTPUT}" echo "1:$ABC:$final_output" 

In other words, use the same method to extract the output as for other information.

+7
source share

All Articles