copy'n'paste Syndicate content Syndicate content

» Access klipper clipboard on CLI under KDE4

Wed, 08/13/2008 - 23:12

Here’s a little script you can save in your path and do things like

  1. # paste current clipboard into file
  2. clipboard > "some_file"
  3. # copy some file into clipboard
  4. cat "some_file" | clipboard

Actually I find it rather useful so I thought I will have to share it.

Since KDE4 D-BUS is used throughout KDE and thus in Klipper as well. IMO they should really rework the output of dbus-send or add some more flags (what about --quiet). Well that’s the reason why the script below is somewhat long. But nothing a little bit of bash+awk magic couldn’t cope with:

  1. #!/bin/bash
  2.  
  3. # check for stdin
  4. # since we don't want to wait endlessly we set a timeout
  5. # a pity `read` only supports seconds and no fractions...
  6. read -t 1 stdin
  7. if [[ "$stdin" != "" ]]; then
  8. # get the rest of stdin
  9. stdin=$stdin$(cat)
  10. # oh, nice - user input! we set that as current
  11. # clipboard content
  12. dbus-send --type=method_call --dest=org.kde.klipper \
  13. /klipper org.kde.klipper.klipper.setClipboardContents \
  14. string:"$stdin"
  15. exit
  16. fi
  17.  
  18. # if we reach this point no user input was given and we
  19. # print out the current contents of the clipboard
  20. # note: I hate the output of dbus, dcop was much easier in that regard!
  21. dbus-send --print-reply --dest=org.kde.klipper /klipper \
  22. org.kde.klipper.klipper.getClipboardContents | awk '
  23. BEGIN { output = ""; }
  24. {
  25. if ( NR > 1 ) {
  26. output = output $0 "\n";
  27. }
  28. }
  29. END {
  30. print substr(output, 12, length(output) - 13);
  31. }'

As usually, save the file (attached below) in your $PATH and make it executable.

PS: Thanks to Martin Vidner for his article on D-BUS btw. - it gave me the proper dbus commands.