Ubuntu – Create a Screen session with a bash script using crontab

bashcommand linecronscriptsserver

I want a .jar file to run every time the server boots up (we're using a VPS), and so I've edited crontab using crontab -e and then adding @reboot bash /home/bash/startserver.sh. But I haven't even gotten to the point where the script works at all.

Here's my script:

#!/bin/bash
screen -S bukkit
cd $HOME/server
java -jar bukkit.jar

The reason that I need to use screen is because when I start bukkit.jar, it goes into a console where I can enter more commands for that program (I'm sure you're all familiar with Minecraft and its servers on this site, though, haha), but I need to be able to do other commands as root and for other programs while it's running, and even close my PuTTY session.

The only problem is that when this script is run, it creates a screen session, but it's ID isn't listed in screen -ls, as the ID is blank. Rather, I have to go to /run/screen/S-root to find the ID and then use the typical screen -X -S $name quit on it.

Maybe this isn't even possible, or maybe there's actually a simpler way to do this (I would love simpler), but I can't figure out why this isn't working. And if this is possible, is it possible to rejoin a session with screen -S bukkit when running a bash script? (Multiple questions, I guess, but thank you so much for your help! (parentheses))

Best Answer

Start screen in detached mode, and make it run your command inside it:

screen -d -m -S bukkit bash -c 'cd $HOME/server && java -jar bukkit.jar'

You might want to create a dedicated script bukkit.sh:

#!/bin/bash -e
cd ~/server
java -jar bukkit.jar

So that if the script becomes more complex you don't have to write a long line for screen, and so the screen command can stay the same, simply:

screen -d -m -S bukkit path/to/bukkit.sh
Related Question