'Keep an app running and if it crashes, restart it. Ubuntu 16

I'm running an Ubuntu 16 server. Mainly I have an application running. I use Plesk, WinSCP and PuTTY to manage the server, the files, and to run this app. The app it's a .jar which I allocate RAM and run.

This app has a console which I run into an screen on PuTTY. If the app crashes, I need to go into that screen and run again the line that allocates RAM and launch the app again.


So here's my question:

Could you help me to see if the script I wrote is wrong or can be better/optimized?

The intention is that if the app crashes, it's automatically launched after some seconds. If the screen is not found because was shut down, the screen has to be made again and so the app launched again. If also it crashes too many times, then I don't know if it would be nice to put some kind of code to prevent restarting all the time something that would crash every time, just in case it starts a loop of crashes.

This app of course it's on a directory of the ftp and I guess that some code parts, of what I exposed, would need the directory path/rute (C:/ftpRoot/mainFolder/anotherFolder/appFolder).

If I need to give you any extra information just tell me and gladly I will.

Thank you all in advance.


Here's the .sh I have for the moment:

for session in $(screen -ls | grep -o '[0-9]\{3,\}\.\S*')
    do
        screen -r DedicatedScreen -p0 -X stuff "&9Server is restarting. \015"
        screen -r DedicatedScreen -p0 -X stuff "stop\015" #Send "stop\r" to the RunningApp console.
    done

counter=0
while [ $(screen -ls | grep -c 'No Sockets foun in') -lt 1 ]; do
    if [ $(( $counter % 10)) -eq 0 ]; then
        echo 'A previous server is in use. Waiting for 10 seconds before starting server ...'
    fi

    sleep 1
    counter=$((counter+1))
done

echo 'Starting Application...'
    
    screen -dmS "DedicatedScreen" java -Xms1024M -Xmx7168M -jar custom_f.jar
    sleep 1
    while [ $(screen -ls | grep -c 'No Sokets found in') -ge 1 ]; do
        sleep 5
        screen -dmS "DedicatedScreen" java -Xms1024M -Xmx7168M -jar custom_f.jar
    done

echo 'Application started.'


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source