2009-05-20 19 views
0

添加到您的命令,我有以下的代码,我致电Google无法参数中的Bash

#!/bin/bash 

q=$1 
open "http://www.google.com/search?q=$q" 

它打开Firefox浏览器的关键字。例如,通过

google cabal 

我想要在命令后面添加一个参数时,将特定的按键添加到命令中。下面是一个例子

google -x cabal 

它搜索的顺序,例如

"cabal is" 

你怎么能添加一个参数到砸向你的命令?

回答

3

由于您有两个信息来源(搜索项和修饰符),我会使用以下内容。它允许使用单个修饰符(-x用于追加“is”并将整个事物放在引号中,-d用于前缀“define:”并将整个事物括在引号中,而-w仅用于添加搜索词以限制您访问wikipedia) 。

请注意,引号的位置由修饰符控制,因为它可能需要引用传递给Google的参数或在该参数外添加搜索项。您完全可以控制网址中生成的内容(确保在发送到产品之前将echo变回open)。

#!/bin/bash 
prepend="" 
append="" 
case "$1" in 
    -h) 
     echo 'Usage: google [-{hxdw}] [<arg>]' 
     echo '  -h: show help.' 
     echo '  -x: search for "<arg> is"' 
     echo '  -d: search for "define:<arg>"' 
     echo '  -w: search for <arg> site:wikipedia.org' 
     exit;; 

    -x) 
     prepend="\"" 
     append=" is\"" 
     shift;; 
    -d) 
     prepend="\"define:" 
     append="\"" 
     shift;; 
    -w) 
     prepend="" 
     append=" site:.wikipedia.org" 
     shift;; 
esac 
if [[ -z "$1" ]] ; then 
    query="" 
else 
    query="?q=${prepend}${1}${append}" 
fi 
echo http://www.google.com/search${query} 

下面是一些样本输出:

pax> google -w "\"bubble sort\"" 
http://www.google.com/search?q="bubble sort" site:.wikipedia.org 

pax> google cabal 
http://www.google.com/search?q=cabal 

pax> google 
http://www.google.com/search 

pax> google -d cabal 
http://www.google.com/search?q="define:cabal" 

pax> google -x wiki 
http://www.google.com/search?q="wiki is" 

pax> google -h wiki 
Usage: google [-{hxdw}] [<arg>] 
     -h: show help. 
     -x: search for "<arg> is" 
     -d: search for "define:<arg>" 
     -w: search for <arg> site:wikipedia.org 

如果不提供一个搜索词,你只得到了谷歌搜索页面。

3
#!/bin/bash 
while getopts "x:" option; do 
    case "$option" in 
    x) keyword="$OPTARG";; 
    esac 
done 
#echo "$keyword" 
open "http://www.google.com/search?q=$keyword" 

The:指定在x是预期的参数之后。

+0

我需要在脚本中放置open-command吗? – 2009-05-20 21:58:29

+0

我向它添加了打开命令。 – seb 2009-05-20 23:45:58

2
#!/usr/bin/env bash 

while [[ $1 = - ]]; do 
    case $1 in 
     -x) shift; query+=" $1 is"  ;; 
     -d) shift; query+=" define:$1" ;; 
     -s) shift; query+=" site:$1" ;; 
     -t) shift; query+=" title:$1" ;; 
     -i) params+="&btnI"   ;; 
     # ... 
     -h) 
      echo "usage: ${0##*/} [-x arg] [-d arg] [-s arg] [-t arg] [-ih]" 
      echo 
      echo " -x: Add '[arg] is' to the google query." 
      echo " -d: Add 'define:[arg]' to the google query." 
      echo " -s: Add 'site:[arg]' to the google query." 
      echo " -t: Add 'title:[arg]' to the google query." 
      echo " -i: Do an I'm Feeling Lucky-search." 
      echo " -h: Show this help text." 
      exit ;; 
    esac 
    shift 
done 

query+="$*" # implode all other arguments into the query string. 

open "http://www.google.com/search?q=$query$params"