I have a script that basically monitors a program of your choosing be it bash or binary and when ever it crashes it restarts, if it crashes more then five times it emails the user.
Now the scripts not 100% finished with the email part but my problem is it you run it through interactive mode it runs fine but when you go through CLI (EX: ./runapp logname appname) on the first crash it wont restart and then wont log it.
Here is my code hope you guys can give me a hand
TYIA
-James
Code:
#!/bin/bash
function backgroundchecker {
((count=0))
if [[ $2 == "" ]]
then
appname=$name
else
appname=$2
fi
if [[ $1 == "" ]]
then
errorfile=$errorlog
else
errorfile=$1
fi
while (true)
do
if ps aux | grep "$appname" | grep -v grep >/dev/null ;
then
sleep 10
else
if [[ $type == "menu" ]]
then
echo "The application \"$appname\" crashed at " `date`
echo "The application \"$appname\" crashed at " `date` >> $errorfile
else
echo "The application \"$appname\" crashed at " `date` >> $errorfile
fi
if [[ $count == "4" ]]
then
echo "ERROR: $appname has crashed 5 times in this session."
echo "ERROR: $appname has now been stopped"
echo "ERROR: $appname's log is now being emailed..."
exit
fi
if [[ -f $appname ]]
then
if [[ $type == "menu" ]]
then
echo "Restarting \"$appname\" at " `date`
fi
echo "Restarting \"$appname\" at " `date` >> $errorfile
bash $appname 2>/dev/null
if [[ "$?" -eq "0" ]]
then
echo >/dev/null
else
$appname 2>/dev/null
if [[ "$?" -eq "0" ]]
then
echo >/dev/null
else
echo "\"$appname\" failed to execute successfully at " `date` >> $errorfile
fi
fi
else
echo "ERROR: Application \"$appname\" not found! " >> $errorfile
fi
((count++))
fi
done
}
function menu {
type="menu"
echo -n "Name of the error log file: "
read errorlog
echo -n "Name of application you would like to run: "
read name
if [[ -f $name ]]
then
bash $name 2>/dev/null
if [[ "$?" -eq "0" ]]
then
backgroundchecker $errorlog $name $type
else
$name 2>/dev/null
if [[ "$?" -eq "0" ]]
then
backgroundchecker $errorlog $name $type
else
echo "$name failed to execute successfully at " `date`
echo "$name failed to execute successfully at " `date` >> $errorlog
fi
fi
else
echo "ERROR: Application \"$name\" not found!"
echo "ERROR: Application \"$name\" not found!" >> $errorlog
fi
}
function cli {
type="cli"
if [[ -f $2 ]]
then
bash $2 2>/dev/null
if [[ "$?" -eq "0" ]]
then
backgroundchecker $1 $2 $type
else
$2 2>/dev/null
if [[ "$?" -eq "0" ]]
then
backgroundchecker $1 $2 $type
else
echo "$2 failed to execute successfully at " `date` >> $1
fi
fi
else
echo "ERROR: Application \"$2\" not found! " >> $1
fi
}
function interactive {
if [[ $2 == "" && $1 == "" ]]
then
menu
else
if [[ $2 == "" || $1 == "--help" ]]
then
echo "Syntax: runapp log_location application"
else
cli $1 $2
fi
fi
}
interactive $1 $2