9

For some scripting, I need to get the word currently under the cursor.

Can xdotool or a similar tool get it?

1
  • Do you mean selected word? Then yes. (But not xdotool) Jun 5, 2016 at 9:07

1 Answer 1

10

How to get the currently selected text

You can get the currently selected text with the command:

echo $(xclip -o -sel)

...but you'd need to install xclip first:

sudo apt-get install xclip

From man xclip:

-o, -out
    prints the selection to standard out (generally for piping to a file or program) 

and:

-selection
    specify which X selection to use, options are "primary" to use XA_PRIMARY (default), "secondary" for XA_SECONDARY or "clipboard" for XA_CLIPBOARD

See also here or, as always, man xclip.


EDIT

Workaround issues with the last selection

From a comment, I understood that xclip outputs the last selection, even if there is nothing selected anymore (e.g. when the file is closed). That seems to be an issue in your situation.

Although xsel also has this issue, it can be worked around: if we make your script not only read the current selection into the script, but also write the same content to a file. We can then check if a the new selection is different from the last selection. If not, we can conclude no new selection is made, and the command most likely produces an outdated selection. We can then tell the script to pass.

An example (using xsel, which has slight advantages in this case):

#!/bin/bash

# make sure the file to store the last selection exists
f=~/.old_sel
touch $f
# get the previous & current selection
old=$(cat "$f"); new=$(xsel -o)

if [ "$old" != "$new" ]; then
  # if selection changed, store the new selection to remember
  echo "$new" > "$f"
  # do the action, whatever that may be
  echo $new
fi

No need to say that you'd need to install xsel:

sudo apt-get install xsel
8
  • Is there a way to do it without selection?
    – user423626
    Jun 5, 2016 at 9:12
  • 1
    @BharadwajRaju That would really surprise me, what is the current application to communicate with? You wouldn't know! It would require some global text recognition on what happens on the screen. And even then..I don't see it happen. Jun 5, 2016 at 9:13
  • Is there a way to find if there is any text currently selected? Because even if there isn't any, xclip returns the last selected text.
    – user423626
    Jun 5, 2016 at 11:58
  • @BharadwajRaju see my update. Jun 5, 2016 at 21:15
  • Sometimes (randomly) it returns Error: Target STRING not available and exits.
    – user423626
    Jun 30, 2016 at 19:07

You must log in to answer this question.