Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export not working (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 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
like image 377
robert Avatar asked Oct 18 '11 00:10

robert


1 Answers

Yes, it is being set. Unfortunately it's being set in the sub-process that is created by $() to run the test_this function 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):

#!/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 only want to call it once, you could 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 for extracting output as you did for the other information.

like image 112
paxdiablo Avatar answered Oct 15 '22 08:10

paxdiablo