8

I'd like to do a one line bash command that automatically does this:

screen -S myserver 
python myserver.py  # inside the new screen
CTRL A, D (detach)

I think this won't work:

screen -S myserver && python myserver.py

because python myserver.py won't be started inside the screen.

2 Answers 2

12

You can detach right after starting a program inside of screen:

screen -dmS myserver python myserver.py

From screen's man page

-d -m Start screen in detached mode. This creates a new session but doesn't attach to it. This is useful for system startup scripts.

3
  • 1
    Thank you very much, very helpful! I also learnt that this works, as a one-liner, to create a screen, start a command, and attach: screen -S myserver python myserver.py (previously I always did screen -S myserver and then typing the command manually).
    – Basj
    Commented Feb 13, 2018 at 22:36
  • How to prevent the screen from terminating when the command is finished ? Thanks
    – KaKi87
    Commented May 3, 2023 at 5:16
  • unix.stackexchange.com/questions/490508/…
    – Stefan M
    Commented May 6, 2023 at 8:05
2

The answer from @Stefan M is good, but is not quite like running a command within the screen, because when the command ends, the whole screen will end. If you actually run a command within the screen, then when it quits, you'll be left with a shell.

You can retain that shell with this:

screen -s "/bin/bash" -dmS myserver; screen -S myserver -X stuff "python myserver.py\n"; 

This will first launch the screen, with a shell, and then send some commands into that shell to run. This will behave exactly as if you typed those commands into the screen yourself.

A more elaborate script is available here: https://unix.stackexchange.com/a/766301/598166

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .