Search Google From Your Terminal

Hey guys, quick one here that I know has been covered to death everywhere.

I just wrote a quick little function for my bashrc to do google searches from bash and the functionality actually surprised me.

I didn’t think about the fact that I’d be able to use the google calculator functions ( with a tiny bit of sanitizing in the code ) and pretty much all the other google services. So it turned out to be much more convenient/useful than I originally thought.

It should be cross platform for OS X and Linux, as long as you’re using bash.


# Search google via chrome from the command line
# No qoutes needed:

# IE: $ s my google search

# Math functions are also available:

# IE:
# s 2 + 2 
# s 2 x 2
# s 2 / 2
# s 2 - 2

s(){

    searchquery=0
    
    # Loop through our parameters and build the search query

    for param in $*
    do  
        if [ "$searchquery" == "0" ]
                then
                        searchquery="$param"

                # Perform as expected when query contains a "+"
                
                elif [ "$param" == "+" ]
                        then
                                searchquery="$searchquery+%2B"
                else
                searchquery="$searchquery+$param"        
        
        fi
    
    done

    
    url="https://www.google.com/search?q=$searchquery"

    
    # Check whether we're on OS X or Linux

    if [ "`uname -a | grep -o Darwin | wc -l`" -gt "0" ]
        then
                open $url
        else
                google-chrome $url
                # This could also be firefox, opera, whatever floats your boat.
    fi



}

Thats about it. You can stick it in your ~/.bashrc or in /etc/bashrc or profile.

The post is short because I tend to over-comment even when I write simple things like this. Everything should be explained in the code block.