I could not figure out how to start a screen session, and in that attached screen session to run a command without human intervention. Expected behavior is:

[me@me ~]# screen -S name -L --mystery_flag 'hostname;echo yes;echo no'
#new screen session
[me@me ~]# hostname
[me@me ~]# echo yes
[me@me ~]# echo no
[me@me ~]#

I looked by only found ways to send commands to a detatched session of screen, or to have the screen session close after it sends a command like screen -S name "command". I would like for the session to stay open, since it will be used to run an interactive script.

  • 1
    Since you give screen a command to run instead of a shell, it will run that command and then terminate, just like it would otherwise run your shell and then terminate when the shell exits. You could try launching a shell as the last command, but I'm currently uncertain whether it understands a list of ;-delimited commands at all (can't test at the moment).
    – Kusalananda
    Dec 2, 2020 at 6:46
  • So then how would you make a script that runs screen, and then a bunch of commands and doesn't terminate afterwards? Is it even possible? Or maybe needs a different program similar to screen?
    – Mesos
    Dec 2, 2020 at 15:25

1 Answer 1


GNU screen takes a number of options, and then an optional command to start within the screen session. If no command is given, the screen session will contain an interactive shell session. The screen session terminates when the command that it runs terminates, no matter whether it's a command given on the command line of screen, or the shell that it otherwise runs.

You have two issues:

  1. You want to run more than a single command.
  2. You want the session to not terminate at the end, but instead leave you in an interactive shell session, within screen.

To solve the first of these, make the command that screen starts be

sh -c 'hostname; echo yes; echo no'

This is a single command that starts an in-line sh -c script. This script runs your commands. You may want to use bash -c in place of sh -c if the script you're running requires bash (your example does not).

To solve the second issue, consider starting an interactive shell as the last step in the list of commands that the sh -c script runs:

sh -c 'hostname; echo yes; echo no; exec bash -i'

The exec bash -i starts an interactive bash shell session (the exec makes it replace the sh -c shell).

Running this within a screen session:

screen sh -c 'hostname; echo yes; echo no; exec bash -i'

GNU screen will terminate once the bash -i shell session terminates.

  • Thanks, this works!
    – Mesos
    Dec 2, 2020 at 16:30

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.