Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 856
Jellby Avatar asked Jan 29 '14 12:01

Jellby


People also ask

What is the command used to make variables available to subshells?

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.

How do you set an environment variable that is accessible from subshell?

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.

What is a subshell command?

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.

How is subshell implemented?

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.


1 Answers

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
like image 163
choroba Avatar answered Oct 11 '22 00:10

choroba