Shell Clipboard Manager

2019-07-27 20:02:45 +0000 UTC

I found myself wanting a way to manage my desktop clipboard similar to the way VIM works with named registers. To be able to store something in a certain clipboard I could then recall when needed.

I settled on using a basic system written in bash that would allow me to name the clips anything I liked.

The script

Here is the bash script in all its glory.

#!/bin/bash
set -euo pipefail

dir=~/.local/share/dlip

dlip_init() {
    if [[ ! -d $dir ]]; then
        mkdir -p $dir
    fi
}

dlip_save() {
    echo -n "Save to: "
    read -r line

    local file="${dir}/${line}"
    echo "Saving to $file"

    xsel -o --clipboard > $file
}

dlip_get() {
    sel=$(find $dir/. -type f -printf "%f\n" | fzf)

    if [[ -z $sel ]]; then
        exit 0
    fi

    xsel -i --clipboard < "${dir}/${sel}"
}

# https://github.com/hlissner/dotfiles/blob/master/base/arch-desktop/bin/urxvt-pass-manager
open_win() {
    local win=$(xdotool getactivewindow)
    xdotool search --onlyvisible --classname urxvt-win windowkill || true
    bspc monitor -f primary
    urxvt -name urxvt-win \
        -bg '#fdf6e3' \
        -fg '#657b83' \
        -geometry 100x16 \
        -e $SHELL \
        -c "$1"

    [[ -n $win ]] && xdotool windowactivate $win
}

dlip_get_menu() {
    open_win "dlip get"
}

dlip_save_menu() {
    open_win "dlip save"
}

[ $# -gt 0 ] || exit 1

command="$1"
shift

dlip_init

case "$command" in
    save)
        dlip_save; exit 0 ;;
    save_menu)
        dlip_save_menu; exit 0 ;;
    get)
        dlip_get; exit 0 ;;
    get_menu)
        dlip_get_menu; exit 0 ;;
    *)
        echo "`basename "$0"` $command: unknown command." >&2
        exit 1
        ;;
esac

How it works

The shell script is added to my PATH and called dlip. It stores the clips in files with a specified name in the folder ~/.local/share/dlip.

Setting a value

To set whatever is in the current clipboard to a named clipboard:

dlip save
# Then enter the name of the file I want to save as

Getting a value

To retrieve a saved value, writing it into the contents of the clipboard:

dlip get
# This then uses fzf to let me select from the list

Integrating with the desktop

This is all well and good but can be a bit clunky especially when dealing with the clipboard outside of a terminal. In order to address this I made some convience shortcuts that work with bspwm window manager and sxhkd hotkey daemon that I run. The idea should be easily transferrable to other WM’s though.

The bindings in sxhkd config look like this:

# get a named clipboard
super + v
    dlip get_menu
# save to a named clipboard
super + x
    dlip save_menu

Here is an example of if in action:

dlip example