Is it possible to access highlighted text via a shell script?

I want to make a keyboard shortcut to use 'espeak' to read highlighted text.


Yes, this is relatively easy, there are plenty of tools for clipboard manipulation, I've used them for filling in apple device registration and email verification along with xdotool… a lot easier than filling in the form 1000 times…

So, setup a shortcut to be /home/bob/bin/speak.sh



xclip -o | xclip -selection clipboard -i
xclip -o | espeak

short: usually you cannot do this (unless the selection was copied to the clipboard)

long: there are a few special cases, e.g., xterm has a feature which (is normally disabled) allows an application to read the selected text via escape sequence. That is described in XTerm Control Sequences:

        Ps = 5 2  -> Manipulate Selection Data.  These controls may
      be disabled using the allowWindowOps resource.  The parameter
      Pt is parsed as
           Pc; Pd
      The first, Pc, may contain zero or more characters from the
      set c  p  s  0  1  2  3  4  5  6  7 .  It is used to construct
      a list of selection parameters for clipboard, primary, select,
      or cut buffers 0 through 7 respectively, in the order given.
      If the parameter is empty, xterm uses s 0 , to specify the
      configurable primary/clipboard selection and cut buffer 0.
      The second parameter, Pd, gives the selection data.  Normally
      this is a string encoded in base64.  The data becomes the new
      selection, which is then available for pasting by other appli-
      If the second parameter is a ? , xterm replies to the host
      with the selection data encoded using the same protocol.
      If the second parameter is neither a base64 string nor ? ,
      then the selection is cleared.

That is, if the allowWindowOps resource is enabled, an application could do something like

printf '\033]52;s;?\007'

and read the selection data as a base64 string. But that's a special case.

Some applications of course copy to the clipboard (see FAQ), but not all. For instance rxvt, etc., use the primary selection. There is no solution which would work everywhere.

Further reading:

  • Your answer is very misleading. Many applications (including xterm!) expose selected text as the primary selection which is immediately visible to other applications that connect to the same X display. – Gilles 'SO- stop being evil' Oct 25 '16 at 21:57
  • To complete your comment, you should provide an example of a scriptable application which will grab the primary selection as requested by OP. – Thomas Dickey Oct 25 '16 at 22:16
  • xclip as in the other answer. Or xsel. – Gilles 'SO- stop being evil' Oct 25 '16 at 22:21

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.