How do I get variable defined in BASH subshell outside?

I'm a BASH shell user (relatively new)
I need to get a variable calculated in a subshell, outside the subshell, when it completes. I can do it, by writing the variable into a file, and then reading the file again when outside the subshell. I've tried lots of things from exporting to environmental variables, but nothing seems to work. Is there a simple way?
A simple example is below.
Thanks,
Gerry :slight_smile:
------------------------------------------

 
#!bin/bash
num=1 # variable defined in BASHSHELL 0
 
( # start of subshell level is BASHSHELL 1
echo $num # this works: gives 1 for the answer
 
inside_num=2
echo $inside_num # this works: gives 2 for the answer
 
# my question is how do I get the value of inside_num to BASHSHELL 0 level?
 
) # end of subshell 
 
echo $inside_num # this doesn't work, it returns nothing 
# since inside_num was defined in BASHSHELL 1
exit 0 

Using file descriptors perhaps?

Something like this (dirty solution)

#!/bin/bash
num=1 # variable defined in BASHSHELL 0

dirty_var="tmpfile"

( # start of subshell level is BASHSHELL 1
echo $num # this works: gives 1 for the answer
 
inside_num=2
echo $inside_num >$dirty_var # this works: gives 2 for the answer
 
# my question is how do I get the value of inside_num to BASHSHELL 0 level?
 
) # end of subshell 
 
inside_num=$(cat $dirty_var)
rm $dirty_var

echo $inside_num # this doesn't work, it returns nothing 
# since inside_num was defined in BASHSHELL 1
exit 0

You cannot define a variable in a subshell and then use it in the parent shell
What you could use is command substitution:

#!/bin/bash
num=1 # variable defined in BASHSHELL 0
 
outside_num=$( 
  inside_num=$((num+1))
  echo "$inside_num"
) # end of subshell 
 
echo $outside_num

--
Or do not use a subshell and use a function.