title: What is the best way keep a bash script looping in the background on startup - Linux?
body: <p>I have created a bash script to record sound input via the line in/mic port of the sound card and when sound is detected via breaking silence it records to a temp file, then date-stamps it in a new file and adds it to a database.</p>
  
  <p>What i need to achieve is a good way of making the script start at boot, keep running the script over and over, and restart if it failed to restart itself. Below is the code i have currently put together from various sources and it works well so far. But i need it to be able to run 24/7 without any user interaction.</p>
  
  <p>This is my first real bash script that i have created so would like a more experienced input to the method i have used and if it is wrong or right.</p>
  
  <p>I did try to daemonize via the start-stop-daemon but ended up with multiple running scripts and sox commands. Currently i have it to execute at boot in rc.local, personally i don't think it is the correct way to restart the script by adding the command for it again at the bottom of the script... but i don't know of any other way.</p>
  
  <p>Any sort of help is greatly appreciated.</p>
  
  <pre><code>#!/bin/bash
  
  #Remove temp file just incase
  rm -rf temp.mp3
  
  #Listen for audio and record
  sox -d /home/user/temp.mp3 silence 1 5 8% 1 0:00:01 8%
  
  #Check if temp.mp3 is greater than 800 bytes so we don't get blank recordings added to the
  #database, if the file is below 800 bytes remove the file and restart.
  for i in /home/user/temp.mp3 ; do
     b=`stat -c %s "$i"`
  if [ $b -ge 800 ] ; then
  
  NAME=`date +%Y-%m-%d_%H-%M-%S`
  TIME=`date +%H:%M:%S`
  FILENAME=/var/www/Recordings/$NAME.mp3
  FILEWWW=Recordings/$NAME.mp3
  mv /home/user/temp.mp3 $FILENAME
  rm -rf temp.mp3
  
  mysql --host=localhost --user=root --password=pass database &lt;&lt; EOF
  insert into recordings (id,time,filename,active,status) values('NULL','$TIME','$FILEWWW','1','1');
  EOF
  
  
  else
  rm -rf /home/user/temp.mp3
  echo 'No sound detected, Restarting...'
  fi
  done
  
  /home/user/vox
  exit 0
  </code></pre>