質問

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?

役に立ちましたか?

解決

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.

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top