15

How do you send keyboard input to a program?

That is, under a Linux GUI, is there a good manual (programmable) way, or tool, of simulating keyboard input on a running program on Linux, so that I can send from the command-line, e.g., "Control-T" to a Firefox process and "echo 'hello'\n" to a Gnome-Terminal process without actually focusing on each of those processes and typing in directly?

OTZ
  • 3,003
  • 4
  • 29
  • 41

4 Answers4

16

xdotool does have a way of sending keystrokes if limited to a focused window:

WID=`xdotool search "Mozilla Firefox" | head -1`
xdotool windowactivate $WID
xdotool key ctrl+l
OTZ
  • 3,003
  • 4
  • 29
  • 41
  • 1
    List of key symbols you can find in `/usr/include/X11/keysymdef.h` file. – jcubic Oct 05 '10 at 13:22
  • Online Documentation can be found here: http://www.semicomplete.com/projects/xdotool/ – Florian F Dec 06 '13 at 15:18
  • Why do you use `head -1`? – qed Mar 08 '14 at 20:58
  • stumbled here for a list of keys, updating comments. Most people don't install dev packages so list here: http://www.tcl.tk/man/tcl/TkCmd/keysyms.htm , and head -n 1 is normally used to get the first match in case you have multiple – bksunday Jul 07 '15 at 13:38
3

It's an old topic, but one still may be looking for this, someone mentioned here solution where window must be activated when using xdotool. However you can specify window and even use xdotool to find it. Here is example I tried to accomplish, change it as you need.

xdotool key --window $(xdotool search --name "Spotify (Premium |Free )?- Linux Preview" | head -n1) ctrl+KP_Down
talonmies
  • 70,661
  • 34
  • 192
  • 269
Chlorek
  • 138
  • 7
  • Didn't work from me, I tried with Audacity `xdotool key --window $(xdotool search --name "Audacity" | head -n1) Ctrl+Q` – Salem Apr 21 '22 at 06:28
2

I've built a Ruby DSL around xdotool to simplify the focusing of windows and simulation of keyboard input. Here's an example, riffing on your original request:

Mani.new(window_manager: :xmonad) do
  window :hello, launch: 'urxvt' do
    run 'echo "hello\n"'
  end

  window :firefox, launch: 'firefox', delay: 1.5 do
    type '{{ctrl+t}}'
  end
end
nsxt
  • 76
  • 1
  • 6
1

I found these two programs xmacro and xremote you may take a look, but it seems that they're not well documented.

I also found this utility xvkbd in answer to this question SO Q&A titled: Sending keycode to Xorg + wine with bash script.

Community
  • 1
  • 1
jcubic
  • 61,973
  • 54
  • 229
  • 402