Google Search from the command line

I won’t go into the details of why you would want to do this, suffice to say that I do and searched for a wee while on the best way to do it. Bizarrely Google’s own CLI tools don’t include search.

The only 3rd-party solutions I could find open the results in a web browser, which isn’t really what I wanted. So I wrote a REALLY ugly one-line script, but it works for me, so why not share. Maybe it will inspire someone with more talent!

It requires curl and vilistextum which aren’t in a default Ubuntu install, for more barebones OS’s you may need to install awk as well.

#!/bin/bash

curl -A "Mozilla/4.0" "http://www.google.com/search?q=$1%20$2%20$3" | vilistextum -k - - | awk 'NR > 23' | less

Then chmod +x it, install the script in /usr/bin and you can search from the commandline by typing [nameOfScript] [search terms]. e.g. to search for “testing 123” I type:
g testing 123

Yes there’s a lot wrong with this, for a start if you want more than 3 search terms you’ll have to add another argument (%20$4) after the q= string. I’m sure there’s a more elegant way of doing it by using $@, or $# to get the number of arguments and combining them all in a loop. But then it becomes a 5-line script rather than 1.

Also the result is not exactly pretty, but if you use a graphical terminal such as gnome-terminal all the links will be clickable and will open in your default browser.

Alternatively you could pipe the result to lynx, which actually parses html properly, but then any links would open in lynx which is not what I wanted:

#!/bin/bash

curl -A "Mozilla/4.0" "http://www.google.com/search?q=$1%20$2%20$3" | lynx --stdin

.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.