Thread: Subshell
View Single Post
  #2   (View Single Post)  
Old 14th January 2016
IdOp's Avatar
IdOp IdOp is offline
Too dumb for a smartphone
 
Join Date: May 2008
Location: twisting on the daemon's fork(2)
Posts: 1,027
Default

Quote:
Originally Posted by J65nko
Please test and let me know
Here is one test:

Code:
% sh --version
GNU bash, version 4.2.53(2)-release (i486-slackware-linux-gnu)
...
% . subshell.sh
setting a=1 ...
About to enter subshell ...
From within subshell the value of a : 1
Assigning 2 to a ...
From within subshell the value of a : 2
Working directory changed to /etc
Leaving subshell
Back home from trip to subshell ...
Value of a : 1
Working directory: /not/etc
as expected. I'll try to post one or two more when I have a good chance.

I wanted to add two other points.

1) In this thread we discovered that sometimes subshells are used in implementing loops. So they may occur in "hidden" ways from which environment variables unexpectedly can not be passed out.

2) Once after running into that trouble, I realized a possible work-around. Instead of using an environment variable, which can't be passed out of the subshell, one could try to use the exit status of the subshell to pass information out. For example, you could bit-map (or otherwise encode) the information to be passed out into the exit status.
Code:
(
# shell does stuff here, and sets STATUS variable
exit $STATUS
)
case $? in
 0)
   ...
   ;;
  1)
   ...
  ;;
  etc...
esac
Reply With Quote