Right now I'm running a process within GNU screen. Screen is started with the command screen -dmS screenname and the attached with screen -r screenname. A process is started in the screen session, and is killed after some time.

How would I have the screen terminate when the process inside has ended?

Note: I wouldn't prefer a loop, so I'm looking for an alternative. Sometimes I start the process with an & exit following it, but that never executes if I use kill -9 pid on the process.

migrated from stackoverflow.com Jul 2 '12 at 9:22

This question came from our site for professional and enthusiast programmers.


Start the process with exec, so it will be the only thing inside the screen (it replaces the shell instead of returning to the shell after it's done).

  • Could you give me an example? – hexacyanide Jul 2 '12 at 0:05
  • After you type screen -r screenname you're put inside the screen at a shell prompt. At that prompt, type exec yourcommand then detach. – Alan Curry Jul 2 '12 at 0:06

Try this:

screen -dmS screenname sleep 5
sleep 3
screen -ls
sleep 3
screen -ls

On the first screen -ls, you should see your screen session. On the second one, it should be gone. Screen will automatically exit when the last window closes. Since you're only running a single program inside screen, the last (and only) window in the screen session will close when the program exits. If you are starting the program by attaching to the screen session and then typing the command at the shell prompt inside the screen session, then screen is waiting for your shell to exit. You can cause this to happen when the program finishes by typing exec PROGRAM instead of just PROGRAM at the shell prompt (actually this will exit the shell and replace it with PROGRAM).

If all you need is the detach ability of screen and nothing else, a lightweight alternative is dtach.


You can start the screen session with the name of a command, e.g. screen -dmS session vim will open a screen session that exits with vim. From within an existing screen session, you can use exec to get the same effect:.

  • 1
    Just a placeholder I used to test. It'll work the same with anything. – Kevin Jul 2 '12 at 0:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.