Copy hook to write to a file
Here is a little Python 3 script that captures clipboard changes and prints them to the terminal:
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
def callback(*args):
print(clip.wait_for_text(), flush=True)
clip = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
clip.connect('owner-change', callback)
Gtk.main()
You can save this file e.g. ...
- as
~/bin/cliplog
(any name inside thebin/
directory in your user's home directory - you might have to create that directory and runsource .profile
first if it doesn't exist yet) if you want it for your user only, -
or as
/usr/local/bin/cliplog
(any name inside/usr/local/bin/
- you needsudo
/ root privileges to save a file there though) if every user on your machine shall have access to it.
Don't forget to make it executable using chmod +x /path/to/wherever/you/saved/cliplog
.
Now you can simply type the command cliplog
(or however you named it) in your terminal and the script above will capture all changes to your clipboard and print the changed content.
Please note that this command runs forever until you interrupt it by pressing Ctrl+C in the terminal. (Yes, it's the same shortcut for copying stuff on the desktop as for sending the SIGINT interrupt signal in the terminal.)
To automatically store this log in a file, simply use Bash's redirection:
cliplog > mylogfile.txt
Or if you want to both see the output and have it saved in a log file, use tee
:
cliplog | tee mylogfile.txt
If you want to append to the log file instead of overwriting it, use >>
or tee -a
instead.