How do you work with variables outsite of the try catch but changing its value inside?
felipegutierrez opened this issue · 4 comments
Hi,
I have some function that change some variable inside the try/catch and return 0 or 1.
My first problem is when I return 0 or 1 it throws an error.
My second problem is: I placed the return 0 or 1 outside of the try/catch, but I change some variable inside the try/catch. And then I cannot see the new value of this variable.
Kind Regards,
Felipe
Please provide some example code. Hard to reason about this without any examples :)
cat testTry.sh
#!/usr/bin/env bash
source "$( cd "${BASH_SOURCE[0]%/*}" && pwd )/lib/oo-bootstrap.sh"
# load the type system
import util/log util/exception util/tryCatch util/namedParameters
# load the standard library for basic types and type the system
import util/class
VALUE="0"
echo "before try: "$VALUE
try {
echo "inside try: "$VALUE
VALUE="1"
echo "inside try: "$VALUE
} catch {
echo "Caught Exception:$(UI.Color.Red) $__BACKTRACE_COMMAND__ $(UI.Color.Default)"
echo "File: $__BACKTRACE_SOURCE__, Line: $__BACKTRACE_LINE__"
Exception::PrintException "${__EXCEPTION__[@]}"
}
echo "after try: "$VALUE
When I execute I cannot work with the variable after try/catch
# ./testTry.sh
before try: 0
inside try: 0
inside try: 1
after try: 0
Unfortunately, a try/catch block creates a subshell. In bash it's currently impossible to affect the parent shell from a subshells, so the only workaround I can think of would be to capture the try/catch stdout in a variable.
Or you can save result to file and update variable after try/catch
is done...
I personally use:
try {
commandToTry > ${HOME}/.result_of_command 2>&1
} catch {
rm -f ${HOME}/.result_of_command
# handle error
}
results=$(<${HOME}/.result_of_command)
rm -f ${HOME}/.result_of_command