title: Bash setting a global variable inside a loop and retaining its value -- Or process substituion for dummies
body: <p>I'm a C/C++ programmer and quite stupid in general (or at least the way bash does things it makes me feel confused). I can't wrap my head around <a href="https://stackoverflow.com/questions/4667509/problem-accessing-a-global-variable-from-within-a-while-loop">process substitution</a>. </p>
  
  <p>I need to define a global boolean, set it somewhere in a loop, and make use of it in global scope. Could someone please explain in the simplest way possible how to adapt the code below to allow me to achieve my use case, simple enough so that I don't have to contort my brain again tomorrow to try and grasp process substitution . </p>
  
  <pre><code># DEFINE HERE
  
  for i in `seq 0 ${DAEMON_COUNT}`;
  do
          if [ ! -d "data$i" ]; then
  # SET HERE
                  echo "data$i does not exist. Creating...";
                  mkdir data$i
          fi
  done
  
  # TEST AND USE HERE
  </code></pre>
  
  <p>to be honest, I don't think bash is up to the task.... the next block looks like this.</p>
  
  <pre><code>echo "-------------------------------------------------------------------------------"
  echo "checking the state of potentially running daemons"
  for i in `seq 0 ${DAEMON_COUNT}`;
  do
          if [ ! -e "data$i/mongod.lock" ] ; then
                  echo "[no lock file] mongod process $i does not exist"
          else
                  echo "[lock file exists] process $i lock file exists "
                  I_PID=`cat data$i/mongod.lock`
  
                  if [ ! ${I_PID} ]; then
                          echo "    [GOOD] lock pid empty"
                  elif [ "`ps -p ${I_PID} | grep ${I_PID}`" ]; then
                          echo "    [GOOD] data1 pid: ${I_PID} running"
                  else 
                          echo "[PROBABLY FATAL] data1 pid: ${I_PID} not running."
                  fi 
          fi
  done
  echo "-------------------------------------------------------------------------------"
  </code></pre>
  
  <p>What I now need is a global array of structs so that I can loop over them and take conditional action to initialize my daemons correctly :/. </p>
  
  <p><a href="http://www.bsdcan.org/2011/schedule/events/234.en.html" rel="nofollow noreferrer">Might just use libc and do this stuff in lua</a>, the only reason I hold back is having to install rocks, I don't like ad-hoc code repositories vomiting whatever they want onto my machine :D </p>