Script copy the content of the clipboard into a file

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?


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