Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I get screen to execute a command and then detach (That is, automatically in a single script without further input beyond initially starting the script)? e.g. I run and it automatically starts a screen session, executes a command, then detaches.

share|improve this question
up vote 38 down vote accepted

This is an easy one:

screen -d -m yourcommand
share|improve this answer
no dice. screen -d -m command, screen -list says no sockets, screen -r no sessions – darkfeline Jul 29 '12 at 2:24
Somehow your command wasn't found, or isn't working correctly in the automatically-created screen environment. Try just doing screen yourcommand without the -d and -m and see how that goes first. – Alan Curry Jul 29 '12 at 2:28
You're sort of right. screen terminates when the command finishes, contrary to my expectations. But your answer does work. – darkfeline Jul 29 '12 at 2:34
You can change that by enabling the zombie option in screen. Put zombie xy in your ~/.screenrc. It should also be possible to enable it for one session only b putting zombie xy in another file and using -c file but for some reason that's not working when I try it. Or just use sh -c 'yourcommand;while :;do sleep 9999; done' – Alan Curry Jul 29 '12 at 2:39
@AlanCurry, Nope, this doesn't work for me either, even though the command runs perfectly (and takes several hours) when run in a screen manually. – Cerin Sep 27 '14 at 3:08

To run a single command in screen and detach, you may try:

screen -dm sleep 10

To run multiple commands, try:

screen -dm bash -c "sleep 10;"

Please note that when a program terminates, screen (per default) kills the window that contained it.

If you don't want your session to get killed after script is finished, add exec sh at the end, e.g.:

screen -dm bash -c 'sleep 5; exec sh'

To list all your sessions, try:

screen -list

Related: Start Unix screen, Run command, Detach.

share|improve this answer
Thanks, but I meant in a script, including the detach part. I've edited my question to help clarify. – darkfeline Jul 29 '12 at 2:14

You must log in to answer this question.

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