我正在尝试制作一个bash函数,该函数将为我搜索终端$_
的最后输出。例如,当我尝试一些东西时,我从终端得到一个错误,而不是在谷歌中复制和粘贴错误,我只要输入google that
,它就会为我搜索错误。
它还将支持打开谷歌主页和随机谷歌搜索。
function google() {
if [ $1 == 'that' ]
then
open /Applications/Google Chrome.app/ "http://www.google.com/search?q= $_";
elif [ $1 == '' ]
then
open /Applications/Google Chrome.app/ "http://www.google.com"
else
open /Applications/Google Chrome.app/ "http://www.google.com/search?q= $@";
fi
}
当我输入google that
时,我得到[
的搜索结果。我不明白为什么它不起作用?
我在osx10上使用Chrome。
- 不要使用
[ $foo == 'bar' ]
,使用[ "$foo" = 'bar' ]
或[[ "$foo" == 'bar' ]]
- 不要用
[ $1 == '' ]
,用[ -z "$1" ]
- 正如jm666所指出的,但也许应该强调更多,
$_
是不是终端上的最后输出,它是一个"[s]特殊变量设置为前一个命令执行的最后参数",所以你的脚本永远不会真正做你想做的。
说了这么多,稍微干净一点的代码段重写可以像这样:
google()
{
local s="$_"
local query=
case "$1" in
'') ;;
that) query="search?q=${s//[[:space:]]/+}" ;;
*) s="$*"; query="search?q=${s//[[:space:]]/+}" ;;
esac
echo open /Applications/Google Chrome.app/ "http://www.google.com/${query}"
}
示例运行:
$ echo "foo bar quux"
foo bar quux
$ google that
open /Applications/Google Chrome.app/ http://www.google.com/search?q=foo+bar+quux
$ google
open /Applications/Google Chrome.app/ http://www.google.com/
$ google foo bar quux
open /Applications/Google Chrome.app/ http://www.google.com/search?q=foo+bar+quux
因为最后一个命令的最后一个参数是[
在做任何事情之前,必须按顺序存储最后一个参数:
function google() {
local lastarg=$_
if [ $1 == 'that' ]; then
open /Applications/Google Chrome.app/ "http://www.google.com/search?q= $lastarg"
...
首先,在bash
中$_
的平均值(见这里)
the last argument of the last command
,所以当你在脚本中使用它时,它会改变。例如,简单的函数
mytest() {
if [ "$1" == 'that' ]
then
echo $_
fi
}
将打印
]
last argument of the last command
(if)
第二个,直接将url添加到google中,作为基础,您需要将空格更改为+
。你不应该在=
和google's query
之间有空格。你的脚本可以很简单:
google() {
gq=$(sed 's/ /+/g' <<<"$*")
open -a /Applications/Google Chrome.app "http://www.google.com/search?q=$gq";
}
,其中sed
行将空格改为+
,所以命令
google some weird search
将改为URL
http://www.google.com/search?q=some+weird+search
在您对上面的脚本进行source
之后,或者将它放入~/中。配置文件,您可以使用它作为:
google $_ #instead of the "that" is shorter anyway :)
打开Chrome浏览器的查询last argument of the last command
,或简单的
google
打开chrome与en "空"搜索,或如上google some weird search
第三,如果您使用open something something_other
, open
将尝试打开这两个东西。所以,如果你想打开Chrome,你应该使用-a applcation
开关。如果您的default
浏览器是Chrome而不是Safari,您可以使用简单的:
open "http://www.google.com/search?q=$gq";
对于我的方法,我使用html2text(可通过许多东西,我使用HomeBrew), Curl和Grep的组合然后,我在BashProfile中创建了以下函数。
goo() { ARGS='' if [ "x$1" != "x" ]; then for arg in $* do ARGS="$ARGS $arg" done else read -p "what do you want to search for: " ARGS fi ARGS=$(echo $ARGS | sed -e 's/ /+/g') printf "nsearching for the following term: $ARGS nn" curl -A Chrome http://www.google.com/search?q=$ARGS | html2text | grep ' 1. | 2. | 3. ' -A 4 -B1 --color }
当我在终端上时,我需要输入的是'goo hello world',这将在谷歌搜索中搜索hello+world,返回前三个谷歌命中。
对于不熟悉Grep的人来说,-A表示'找到匹配后的行',-B表示之前的行。颜色将突出显示输出中的"匹配"项。
由于我似乎花了很多时间在终端上,我发现这个命令非常有用。