How to keep the window opened even after the command returned or is killed?

Solution 1:

Answer

You need to let screen know that you want a shell running in the new window with a command running in that shell. The simplest way (that I know) to accomplish this is to create the window separately from running the command in it:

screen -S session_name -X screen -t tab_name
screen -S session_name -p tab_name -X stuff "command_to_run \r"

Example:

screen -S test -X screen -t htop_tab
screen -S test -p htop_tab -X stuff "htop\r"

Notes:

  • The \r is there to simulate hitting the return key.
  • stuff will let you interact with any running process in that window

Explanation

The difference between the manual method and the command you are using is:

  • When you create a new window manually, you are creating a window with an interactive shell running in it, and then you type a command in the shell to start a program. When you kill that program, it goes back to the shell and you can do whatever you want.
  • Your command, on the other hand, is instructing screen to create a new window with the provided command running in it (i.e. don't run a shell), so when you kill it, there is no process running in the window and it closes

Relevant excerpts from the screen man page:

In the Default Key Bindings section:

  C-a c,             (screen)          Create a new window with
  C-a C-c                              a  shell  and  switch to
                                       that window.

In the description of the internal screen command:

If a command is specified after "screen", this command (with the given arguments) is started in the window; otherwise, a shell is created.