Using Splunk from the command line

Almost everything that can be done via the web interface can also be accomplished via the command line. For an overview, see the output of /opt/splunk/bin/splunk help. For help on a specific command, use /opt/splunk/bin/splunk help [commandname].

The most common action performed on the command line is search. For example, have a look at the following code:

$ /opt/splunk/bin/splunk search 'foo'
2012-08-25T20:17:54 user=user2 GET /foo?q=7148356 uid=MzA4MTc5OA
2012-08-25T20:17:54 user=user2 GET /foo?q=7148356 uid=MzA4MTc5OA
2012-08-25T20:17:54 user=user2 GET /foo?q=7148356 uid=MzA4MTc5OA  

The things to note here are as follows:

Most use cases for the command line involve counting events to output to other systems. Let's try a simple stats call to count instances of the word error over the last hour by the host:

$ /opt/splunk/bin/splunk search 'earliest=-1h error | stats count by host'  

This produces the following output:

------------ -----
host2 3114
vlb.local 3063

The things to note in this case are as follows:

To retrieve the output as CSV, try the following code:

$ /opt/splunk/bin/splunk search 'earliest=-1h error | stats count by host' -output csv -preview false  

This gives us the following output:

count,host
3120,host2
3078,"vlb.local"  

Note that if there are no results, the output will be empty.