How to create a screen executing given command?

The problem is that using the 'exec' screen command does not start a shell. 'cd' is a shell builtin, so you need a shell for it. Also, you need a shell that remains running so that screen does not terminate.

You can use the -X option to screen to send commands to a running screen session, and the 'stuff' command to send keystrokes to the current window. Try this:

screen -dmS new_screen sh
screen -S new_screen -X stuff "cd /dir
"
screen -S new_screen -X stuff "java -version
"

Yes, you need to put the quotes on the next line in order for the commands to be executed.


I wanted to launch remote screens from within a bash script with some variables defined inside the bash script and available inside screen. So what worked for me was

#!/bin/bash
SOMEVAR1="test2"
# quit existing if there is one running already, be careful
screen -D -RR test1 -X quit || true
screen -dmS test1
screen -r test1 -p 0 -X stuff $"echo ${SOMEVAR1} ^M"

Where the return character, ^M, you need to enter using vim as

i CTRL-V ENTER ESCAPE

You create a screen with a name and in detached mode:

screen -S "mylittlescreen" -d -m

Then you send the command to be executed on your screen:

screen -r "mylittlescreen" -X stuff $'ls\n'

The stuff command is to send keystrokes inside the screen. The $ before the string command is to make the shell parse the \n inside the quotes, and the newline is required to execute the command (like when you press enter).

This is working for me on this screen version:

$ screen -v

Screen version 4.00.03jw4 (FAU) 2-May-06

Please see man screen for details about the commands.


screen -dmS screen_name bash -c 'sleep 100'

This will create new screen named screen_name. And inside the screen it will sleep for 100 seconds.

Note that if you type some command in place of sleep 100 which terminates immediately upon execution, the screen will terminate as well. So you wont be able to see the screen you just created

Tags:

Gnu Screen