Can't add parameter to your command in Bash
I have the following code which I call google
#!/bin/bash
q=$1
open "http://www.google.com/search?q=$q"
It opens Firefox with a keyword. For instance,
google cabal
I want special keys to be added to the command when I put the parameter after the command. Below is an example
google -x cabal
It searches for a sequence like
"cabal is"
How do I add a parameter to your command in Bash?
a source to share
Since you have two sources of information (search query and modifier), I would use the following. It allows a single modifier ( -x
for adding "is" and enclosing everything in quotes -d
for the "define:" prefix and enclosing the entire object in quotes and -w
for simply adding a search term to restrict you to wikipedia).
Note that the placement of the quotes is controlled by the modifier, as you may need to specify an argument passed to Google or add your search terms outside of that argument. You are in complete control of what was generated in the url (make sure you check it echo
back in open
before submitting to production).
#!/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}
And here are some examples:
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
If you don't provide a search term, you just get a google search page.
a source to share
#!/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"
a source to share