Search code examples
bashdash-shell

Loop control from within a subshell


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.


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