Get word under cursor in X11

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

Can xdotool or a similar tool get it?


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