What is the best way to keep a bash script loop in the background at startup - Linux?

I created a bash script to record sound input through the line port / microphone of a sound card, and when sound is detected through a silence violation, it is written to a temporary file, then it writes the date to a new file and adds it to the database.

What I need to do is a good way to start the script at boot, continue to run the script again and again, and reboot if it does not restart. Below is the code that I have compiled from various sources, and it still works. But I need it to be able to work 24/7 without any user interaction.

This is my first real bash script that I created, so I would like to get a more experienced input to the method that I used, and if it is incorrect or correct.

I tried to execute daemonize via start-stop-daemon, but ended up with several running scripts and sox commands. I currently have this to execute when loading into rc.local, personally I don’t think this is the right way to restart the script by adding a command for it again at the bottom of the script ... but I don’t know another way.

Any help is appreciated.

#!/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 << 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
+3
source share
3 answers

To restart the script, you can call it crontab crontab howto

+1
source

Daemonizing script? , script . , , , . , .

Else cron, .

+1

@Gurubaran , , , , fork, sox , , sox incase. ? . , , . script start-stop-daemon

#!/bin/bash

pkill sox
function vox() {
rm -rf /home/user/temp.mp3
sox -d /home/user/temp.mp3 silence 1 5 4% 1 0:00:01 4%
wait

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 /home/user/temp.mp3

mysql --host=localhost --user=root --password=pass database << EOF
insert into recordings (id,time,filename,active,status) values('NULL','$TIME','$FILEWWW','1','1');
EOF

else
rm -rf /home/user/temp.mp3
fi
done
vox 
}
vox 
0

All Articles