Search code examples
macosterminalbashpbcopy

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?


Solution

  • 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.