title: Bash - how to set variable within an if [] condition and use outside
body: <p>I'm trying to get my head around this. I have a basic Bash script:</p>
  <pre><code>#!/bin/bash
  
  do_exit=0
  
  while [ &quot;$do_exit&quot; == 0 ] ; do
  
          echo $do_exit
  
          do_exit=1
  
  done
  </code></pre>
  <p>This works. However, when I want to set <code>do_exit=1</code> inside an <code>if</code> condition:</p>
  <pre><code>#!/bin/bash
  
  do_exit=0
  
  while [ &quot;$do_exit&quot; == 0 ] ; do
  
      free=`free -m | grep Mem | awk '{print $4}'`
  
      if [ &quot;$free&quot; -gt 0 ]
      then
  
          echo $do_exit
  
          do_exit=1
  
      fi &amp; sleep 5;
  
  done
  </code></pre>
  <p><code>$do_exit</code> is ALWAYS 0 ... so never exists. What am I doing wrong? I'm have the same issue with &quot;breaking&quot; and &quot;exit 0&quot; when I want to kill te script - it just carries on!)</p>
  <p>I must be misunderstanding how variables work in Bash? In Perl (my normal programing language), you can set variables anywhere (with the exception of explicitly setting them in a function)</p>