I want to use subshells for making sure environment changes do not affect different iterations in a loop, but I'm not sure I can use loop control statements (break
, continue
) inside the subshell:
#!/bin/sh
export A=0
for i in 1 2 3; do
(
export A=$i
if [ $i -eq 2 ]; then continue ; fi
echo $i
)
done
echo $A
The value of A
outside the loop is unaffected by whatever happens inside, and that's OK. But is it allowed to use the continue
inside the subshell or should I move it outside? For the record, it works as it is written, but maybe that's an unreliable side effect.
To make a variable available in a subshell (or any other subprogram of the shell), we have to “export” the variable with the export command.
The easiest way to set environment variables is to use the export command. Using export, your environment variable will be set for the current shell session. As a consequence, if you open another shell or if you restart your system, your environment variable won't be accessible anymore.
A subshell is a separate instance of the command processor -- the shell that gives you the prompt at the console or in an xterm window. Just as your commands are interpreted at the command-line prompt, similarly does a script batch-process a list of commands.
The subshell is started within the same script (or function) as the parent. You do this in a manner very similar to the code blocks we saw in the last chapter. Just surround some shell code with parentheses (instead of curly braces), and that code runs in a subshell.
Just add
echo "out $i"
after the closing parenthesis to see it does not work - it exits the subshell, but continues the loop.
The following works, though:
#! /bin/bash
export A=0
for i in 1 2 3; do
(
export A=$i
if [ $i -eq 2 ]; then exit 1 ; fi
echo $i
) && echo $i out # Only if the condition was not true.
done
echo $A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With