Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Can you simply wrap the entire loop in a subshell?

#!/bin/sh
export A;
A=0
(
    for i in 1 2 3; do
        A=$i
        if [ $i -eq 2 ]; then continue ; fi
        echo $i
    done
)
echo $A

Note also that you don't need to use export every time you assign to the variable. export does not export a value; it marks the variable to be exported, so that any time a new process is created, the current value of that variable will be added to the environment of the new process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top