2

Is there a way to read the current terminal content (visible window, or full buffer, whatever it's easier) programmatically?

I need this because I'm trying to develop a program which, after executing an arbitrary command, works with its output. I stress after - I know pipes are used for this, but the purpose of the program is avoiding that.

A possible solution would be a combination of a programmatic Select all followed by an xsel invocation, although I don't know any way to perform the first operation [in Gnome Terminal].

Marcus
  • 961
  • 1
    Would it work for you to do a "select all" in the terminal window and copy everything to the clipboard, then start your program that reads from the clipboard? – Philippos May 31 '17 at 08:46
  • 1
    @Philippos if the "select all" is done manually, then it's not a programmatic solution :-) – Marcus May 31 '17 at 08:55
  • @Kusalananda it is a very similar question. it would be effectively duplicate if somebody knowledgeable would confirm that reading from the current terminal (asked in this question) is effectively the same (in other words, not generally possible) as reading from another terminal (asked in the proposed question). – Marcus May 31 '17 at 08:58
  • 1
    @Marcus You don't need to do it manually, you can script it, using something like xdotool to send keystrokes to your terminal. If you can't copy the screen with keystrokes in gnome terminal, you can do it in a screen session and do a :hardcopy there. – Philippos May 31 '17 at 09:20
  • 1
    @Philippos if it can be scripted, in any form (eg. with xdotool as you mentioned), put a brief summary as answer, an I'll accept it! – Marcus May 31 '17 at 10:19

1 Answers1

1

You can do it with a script using screen and xdotool.

This could be your outputworker.sh:

#!/bin/sh
$1
xdotool key --clearmodifiers ctrl+a colon h a r d c o p y space o u t p u t Return Return
your_command output

Then start screen and do outputworker.sh command the command gets executed, <ctrl-a>:hardcopy output and a return is sent to your screen session, producing a file called output, which you can use in your other program that works with the output.

Edit: The second Return keeps screen from waiting for a timeout while displaying the output from the hardcopy.

Philippos
  • 13,453