Save Clipboard History in Just 30 Lines of Code

Save Clipboard History in Just 30 Lines of Code

本文同时提供阅读于:简体中文

   Cover Image by Luba Ertel

In daily work or life, copy and paste are highly used. Sometimes you suddenly need the content you copied before, and it would be convenient if you have the history for reading and searching.

A simple shell script can do that!

When the script runs in background, it reads the clipboard every 2 seconds, compare the local saved record content, append current clipboard content the end of file if it has not been saved.

Files are named with dates (can easily modified it in the followed script, see OUTPUT_FILE) for easy storage and archiving.

Implementation

Create a clipboard.sh script file

clipboard.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/bin/bash

DATE=$(date +%Y-%m-%d)

OUTPUT_FILE=~/Documents/$DATE.txt

if [ ! -f "$OUTPUT_FILE" ]; then
touch "$OUTPUT_FILE"
fi

while true; do

CURRENT_DATE=$(date +%Y-%m-%d)
if [ "$DATE" != "$CURRENT_DATE" ]; then
DATE=$CURRENT_DATE
OUTPUT_FILE=~/Documents/$DATE.txt
fi

if [ ! -f "$OUTPUT_FILE" ]; then
touch "$OUTPUT_FILE"
fi

CLIPBOARD_CONTENT=$(pbpaste)

if ! grep -Fxq "$CLIPBOARD_CONTENT" "$OUTPUT_FILE"; then

echo -e "$CLIPBOARD_CONTENT\n" >>"$OUTPUT_FILE"

fi

sleep 2
done

Give executable permissions to clipboard.sh

1
chmod +x clipboard.sh

Run

1
./clipboard.sh

Read

You can use Shell or an editor (such as VS Code) to view the document contents saved by the script.

tail
1
tail -f ~/Documents/2024-09-03.txt

There are already some very useful clipboard history plugins on the market.

Raycast

PasteNow

The pro version of PasteNow supports iCloud synchronization, which is more user-friendly for viewing history across devices.

Save Clipboard History in Just 30 Lines of Code

https://thelynan.com/clipboard-history/

Author

Lynan

Posted on

2024-09-03

Licensed under

Comments