如何在 bash 函数中使用 pbcopy?可以脚本化吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17079749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use pbcopy in a bash function? Can it be scripted?
提问by JP Lew
I often find myself copying history commands to my clipboard using this:
我经常发现自己使用以下命令将历史命令复制到剪贴板:
echo !123 | pbcopy
echo !123 | pbcopy
This works fine from the Terminal. Assuming !123 = cd .., it looks something like this:
这在终端上运行良好。假设!123 = cd ..,它看起来像这样:
$ echo !123 | pbcopy
echo cd .. | pbcopy
//result: `cd ..` is in the clipboard
To make life easier, I added this bash function to my .bashrc:
为了让生活更轻松,我在我的 .bashrc 中添加了这个 bash 函数:
function pb() {
echo | pbcopy
}
This command would be invoked, ideally, like this: pb !!. However, this doesn't work. Here is what happens:
这个命令会被调用,理想情况下,像这样:pb !!。但是,这不起作用。这是发生的事情:
$ 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'
alias pb='echo !! | pbcopy'
Any pointers?
任何指针?
回答by Samveen
Your function is somewhat wrong. It should use $@instead of $1
你的函数有点错误。它应该使用$@而不是$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 aliasdoesn'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.
为了解释为什么alias不起作用,!!is 在单引号内,如果!!没有引用,则会发生历史替换。由于它是命令历史记录的替代品,根据定义是交互式的,因此将其保存到变量和别名中非常棘手。
回答by Lri
You could also use fc -l -1or history -p '!!'to print the last history entry:
您还可以使用fc -l -1或history -p '!!'打印最后一个历史条目:
pb() {
[[ $# = 0 ]] && local n=-1 || local n=" "
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.
如果 LC_CTYPE 是 C,pbcopy 会混淆非 ASCII 字符。虽然默认情况下终端和 iTerm 将区域设置变量设置为类似 en_US.UTF-8 的内容。

