How to create a screen executing given command?

Alex Abdugafarov picture Alex Abdugafarov · Aug 13, 2011 · Viewed 69.4k times · Source

i'm fairly new in *nix. Is there a way to create a screen, which will immediately execute a given command sequence (with their own arguments)? Two hours of googling yields nothing - perhaps because I can't clearly state the question.

I hope for something like

screen -dmS new_screen exec "cd /dir && java -version"

I am using screen v4.00.03 and CentOS 5.5 (kernel ver. 2.6.18-194.26.1.el5.028stab079.2)

Answer

kR105 picture kR105 · Dec 13, 2013

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 $ before the 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.