I want to write a shell script which copies the contents of the clipboard (plain-text only) when the previous content changes. When I launch the script each time I copy something (so the content of the clipboard changes) the script copies the new values into a file.

I wrote a script which works correctly:

#!/bin/bash
prev=" "
while true
do
curr=$(pbpaste)
if [ "$curr" != "$prev" ]
then
   echo -n " " >> /Users/davide/desktop/file   
echo -n $curr >> /Users/davide/desktop/file     
fi
done

I don't like this solution very much. There must be different ways to solve this problem.

1) Get the content of the clipboard, store into a variable and compare this value with the current value of the clipboard (my solution.)

2) Detect key pressed CMD+C. When the user presses CMD+C (shortcut for copy something into the clipboard) almost certainly the content of clipboard changes, but I don't know if is possible to detect the keystroke without installing additional libraries.

3) See the process.

Processes associated to copy action CMD+C

PBOARD process info

Can monitor the cpu or mem usage of the pboard process (when copying something into the clipboard the value of this percentage change)?

Or (I don't know if is it possible) I can see to address space of the process?

So my question is this:

In your opinion, is there a better alternative to the script which I wrote, considering the alternatives 2 and 3?

  • This sounds like a nice proof of concept for malware to look for passwords on the clipboard. I'm guessing this will be squashed sooner or later and you'll need to get an entitlement to snoop on clipboard changes. We'll see what comes out of WWDC on the privacy front - perhaps this will be possible still for a bit – bmike Jun 4 at 17:48
  • Wrt your Option #2, please read this for some ideas. Also, read this post – Seamus Jun 4 at 17:56
  • How are you going to "watch" for changes to the clipboard? To do this, you need something more than a script. – Allan Jun 4 at 17:58
  • There's an open-source keystroke logger for Macs that will have some code to get you started. – Seamus Jun 4 at 18:06

A product like this already exists and is available free on the App Store - Flycut.

From their Github project page:

Save the clipboard history item currently displayed to a file, closing the Bezel. Delete the item from the clipboard history if capital S was pressed. Clipping is saved to a file on the Desktop, akin to how Screen Shots are saved by OS X. e.g. "Desktop/Clipping 2015-07-15 at 08.35.10.txt

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.