Query Google Finance From the Command Line
This is a one line bash script I wrote to query a stock’s price from Google Finance. It uses wget to get the HTML page from Google Finance and then grep and cut to extract the stock’s price. The script is based on the current HTML format of the Google Finance pages and might not work if Google decide to change this format (It’s easy to modify, though).
To have the script:
Open your favorite text editor (mine is vim), and type/paste this:
1
2
3 #!/bin/bash
wget -nv -O - "http://finance.google.com/finance?q=$@" 2>&1| \
grep "class=\"pr\"" | cut -d">" -f2 | cut -d"<" -f1
save the file as (say) gfinance.
(A short explanation about the command:
wget gets an html page and return the output. the -nv flag is for “no-verbose”, so the wget command won’t display the progress bar and other unneeded stuff (unneeded for our purpose). the “-O -” flag tells wget to print the output to stdout (instead of saving it in a file).
the $@ includes all the arguments that the script received. so, if you type for example “gfinance a b”, then $@ includes “a b”.
2>&1 means: “Redirect file descriptor 2 (STDERR) to the same place where file descriptor 1 (STDOUT) is redirected”.
grep looks for the string class=”pr” in the stream passed it through the pipe and displays only the lines of the stream including this string.
cut -d”>” -f2 is to say: Divide the stream into separate strings according to the delimiter “>” and show only the second field.
That’s it. If it’s not obvious, try building the command one pipe stage at a time, and see the output, then you’ll see why wee need the next pipe.)
Now, to make it executable type this in the terminal (after you make your current directory the one which includes the script):
chmod +x gfinance
To use it from anywhere I usually move my scripts to /usr/local/bin/ :
sudo mv gfinance /usr/local/bin/.
That’s it. Now to query a stock just use something similar to:
gfinance MLNX
or:
gfinance Intel Corporation
Of course, this script can be optimized and extended to print more info, but it’s 3:40 AM and I want to sleep
Enjoy.
If you enjoyed this post, make sure you subscribe to my RSS feed!Related posts:
Leave a Reply
About Me
Tags
My Twitter
Categories
- Algorithms
- Bash
- BlackBerry
- Collaboration
- Command Line
- Cool Tricks
- Easter Eggs
- Ebooks
- Firefox
- Hardware
- Humor
- Linux
- Linux Development
- Linux Kernel
- Networks
- Open Knowledge
- Other
- Productivity
- Programming
- Science
- Security
- Shell Scripts
- Short Posts
- Thoughts
- Tools
- Vim
- Web Development
- Websites
Popular Posts
Calendar
Archives
- March 2010 (1)
- January 2010 (1)
- December 2009 (2)
- September 2009 (13)
- July 2009 (1)
- June 2009 (6)
- May 2009 (4)
- March 2009 (18)
- February 2009 (10)
- January 2009 (10)
- December 2008 (7)
- November 2008 (8)
- October 2008 (1)
- August 2008 (1)
- July 2008 (1)
- June 2008 (2)

Me @ Social Media