Linux – Send Command to Detached Screen and Get Output

gnu-screenlinuxUbuntu

I've been searching to find a way to send a command to a detached screen session. So far, so good. This is what I've come up with:

$ screen -S test -p 0 -X stuff 'command\n'

This command works as it should. But, I would like the output from it too, echoed straight in front of my eyes (no need for a .log file or something, I just want the output).

Using the screen -L command, is not an option.

Best Answer

Use a first in first out pipe:

mkfifo /tmp/test

Use a redirect operator. Redirect command's output to /tmp/test for example like this:

screen -S test -p 0 -X stuff 'command >/tmp/test\n'

Then in another shell

tail -f /tmp/test.

Note you may also want to redirect error messages using the 2>&1 operator.

Example

As requested in the comments, let's assume we have a php script accepting user input and printing the server load on the input of "status":

# cat test.php
<?php
  $fp=fopen("php://stdin","r");
  while($line=stream_get_line($fp,65535,"\n")) 
  {
    if ($line=="status") {echo "load is stub";} 
  } 
  fclose($fp);
?>

You create two fifos:

 # mkfifo /tmp/fifoin /tmp/fifoout

You call a screen:

screen

In another console, let's call it console 2 you find out the name of your screen:

# screen -ls
There is a screen on:
        8023.pts-3.tweedleburg  (Attached)
1 Socket in /var/run/screens/S-root.

In console 2 you send the command to the screen:

 # screen -S 8023.pts-3.tweedleburg -p 0 -X stuff 'php test.php </tmp/fifoin >/tmp/fifoout\n'

you see the command appearing in the screen. Now in console 2 you can send commands to your php process:

echo "status" >/tmp/fifoin

and read from it:

# cat /tmp/fifoout
load is stub
Related Question