title: Bash - redirect stdout and stderr to files with background process
body: <p>I've created a simple init script for an application I'm building. The start part of the script looks like this:</p>
  
  <pre><code>user="ec2-user"
  
  name=`basename $0`
  pid_file="/var/run/python_worker.pid"
  stdout_log="/var/log/worker/worker.log"
  stderr_log="/var/log/worker/worker.err"
  
  get_pid() {
      cat "$pid_file"
  }
  
  is_running() {
      [ -f "$pid_file" ] &amp;&amp; ps `get_pid` &gt; /dev/null 2&gt;&amp;1
  }
  
  case "$1" in
      start)
      if is_running; then
          echo "Already started"
      else
          echo "Starting $name"
          cd /var/lib/worker
          . venv/bin/activate
          . /etc/profile.d/worker.sh
          python run.py  &gt;&gt; "$stdout_log" 2&gt;&gt; "$stderr_log" &amp;
          echo $! &gt; "$pid_file" 
          if ! is_running; then
              echo "Unable to start, see $stdout_log and $stderr_log"
              exit 1
          fi
          echo "$name running"
      fi
  </code></pre>
  
  <p>I'm having trouble with this line:</p>
  
  <pre><code>python run.py  &gt;&gt; "$stdout_log" 2&gt;&gt; "$stderr_log" &amp;
  </code></pre>
  
  <p>I want to start my application with this code and redirect the outputs to the files specified above. However, when I include the <code>&amp;</code> to make it run in the background, nothing appears in the two log files. BUT, when I remove the <code>&amp;</code> from this line, the log files get data. Why is this happening?</p>
  
  <p>Obviously I need to run the command to make it run as a background process in order to stop the shell waiting. </p>
  
  <p>I am also sure that the process is running when I use the &amp;. I can find it with a <code>ps -aux</code> :</p>
  
  <pre><code>root     11357  7.0  3.1 474832 31828 pts/1    Sl   21:22   0:00 python run.py
  </code></pre>
  
  <p>Anyone know what I'm doing wrong? :)</p>