Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use pbcopy in a bash function? Can it be scripted?

I often find myself copying history commands to my clipboard using this:

echo !123 | pbcopy

This works fine from the Terminal. Assuming !123 = cd .., it looks something like this:

$ echo !123 | pbcopy
echo cd .. | pbcopy
    //result: `cd ..` is in the clipboard

To make life easier, I added this bash function to my .bashrc:

function pb() {
    echo $1 | pbcopy
}

This command would be invoked, ideally, like this: pb !!. However, this doesn't work. Here is what happens:

$ pb !123
pb cd .. | pbcopy
    //result: `!!` is in the clipboard

No matter what history command I invoke, it always returns !! to the clipboard. I tried making an alias too, but that shares the same problem:

alias pb='echo !! | pbcopy'

Any pointers?

like image 500
JP Lew Avatar asked Jun 13 '13 05:06

JP Lew


People also ask

What is pbcopy in Linux?

The Pbcopy command will copy the standard input into clipboard. You can then paste the clipboard contents using Pbpaste command wherever you want. Of course, there could be some Linux alternatives to the above commands, for example Xclip. The Xclip utility is similar to Pbcopy.

What is OSX Pbcopy command?

pbcopy will allow you to copy the output of a command right into your clipboard. Vice-versa for pbpaste — it will allow you to paste your clipboard right into your terminal.


2 Answers

You could also use fc -l -1 or history -p '!!' to print the last history entry:

pb() {
  [[ $# = 0 ]] && local n=-1 || local n="$1 $1"
  fc -l $n | cut -d' ' -f2- | printf %s "$(cat)" | LC_CTYPE=UTF-8 pbcopy
}

If LC_CTYPE is C, pbcopy garbles up non-ASCII characters. Terminal and iTerm set the locale variables to something like en_US.UTF-8 by default though.

like image 127
Lri Avatar answered Oct 04 '22 19:10

Lri


Your function is somewhat wrong. It should use $@ instead of $1

that is

function pb() {
    echo "$@" | pbcopy
}

The result:

samveen@minime:/tmp $ function pb () { echo "$@" | pbcopy ; }
samveen@minime:/tmp $ pb !2030
pb file `which bzcat`
    //result: `file /bin/bzcat` is in the clipboard
samveen@minime:/tmp $

To explain why the alias doesn't work, the !! is inside single quotes, and history replacement happens if !! isn't quoted. As it is a replacement on the command history, which is interactive by definition, saving it into variables and aliases is very tricky.

like image 42
Samveen Avatar answered Oct 04 '22 19:10

Samveen