Skip to content

Instantly share code, notes, and snippets.

@jrhawley
Forked from RichardBronosky/README.MD
Created October 4, 2019 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrhawley/82726069f95555da43746c9acfb65a7f to your computer and use it in GitHub Desktop.
Save jrhawley/82726069f95555da43746c9acfb65a7f to your computer and use it in GitHub Desktop.
cb - A leak-proof tee to the clipboard - Unify the copy and paste commands into one intelligent chainable command.

cb

A leak-proof tee to the clipboard

This script is modeled after tee (see man tee).

It's like your normal copy and paste commands, but unified and able to sense when you want it to be chainable

Examples

Copy

$ echo -n $(date) | cb
# clipboard contains: Tue Jan 24 23:00:00 EST 2017
# but, because of `echo -n` there is no newline at the end

Paste

# clipboard retained from the previous block
$ cb
Tue Jan 24 23:00:00 EST 2017
# above there is a newline after the output for readability
# below there is no newline because cb recognized that it was outputing to a pipe and any alterations would "contaminate" the data
$ cb | cat
Tue Jan 24 23:00:00 EST 2017$ cb > foo
# look carefully at this   ^^ that's a new $ prompt at the end of the content exactly as copied
$ cat foo
Tue Jan 24 23:00:00 EST 2017

Chaining

$ date | cb | tee updates.log
Tue Jan 24 23:11:11 EST 2017
$ cat updates.log
Tue Jan 24 23:11:11 EST 2017
# clipboard contains: Tue Jan 24 23:11:11 EST 2017
#!/bin/bash
if [[ -p /dev/stdin ]]; then # stdin is a pipe
p0=1
else
p0=0
fi
if [[ -t 0 ]]; then # stdin is a tty
t0=1
else
t0=0
fi
if [[ -t 1 ]]; then # stdout is a tty
t1=1
else
t1=0
fi
if [[ -f /proc/version ]] && grep -q Microsoft /proc/version; then
os="WSL"
else
unameOut="$(uname -s)"
case "${unameOut}" in
Linux*) os=LINUX;;
Darwin*) os=MAC;;
CYGWIN*) os=CYGWIN;;
esac
fi
LINUX_copy(){
cat | xclip -selection clipboard
}
LINUX_paste(){
xclip -selection clipboard -o
}
WSL_copy(){
cat | /mnt/c/Windows/System32/clip.exe
}
WSL_paste(){
/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe Get-Clipboard | sed 's/\r//'
}
CYGWIN_copy(){
cat > /dev/clipboard
}
CYGWIN_paste(){
cat /dev/clipboard
}
MAC_copy(){
cat | pbcopy
}
MAC_paste(){
pbpaste
}
if [[ $p0 -eq 1 || $t0 -eq 0 ]]; then # stdin is pipe-ish
${os}_copy # so send it to the clipboard
if [[ $t1 -eq 0 ]]; then # also, stdout is not a tty (meaning it must be a pipe or redirection)
${os}_paste # so pass that pipe/redirection the content of the clipboard (enables `man tee` like chaining)
fi
else # stdin is not a pipe
${os}_paste # so output the clipboard
if [[ $t1 -eq 1 ]]; then # stdout is a tty (so we don't have to be strict about not altering the output)
echo # prevent the prompt from being on the same line
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment