Golang : Execute shell command

A programming language will not be complete if there is no way for the developer to execute shell command. In this tutorial, we will show you how to execute a shell command in Go language.

We will use the dig command to retrieve the name servers of a website and output them.

Very often, dig command should be installed by default on most *nix based operating system. In case there is no dig command available, you can install it with the sudo yum install bind-utils or search for equivalent installation instruction for installing the BIND package. For Windows BIND package please download from http://www.isc.org


 package main

 import (

 func main() {

  cmd := exec.Command("dig", "any", "google.com")
  out, err := cmd.Output()

  if err != nil {


Execute > go run exec.go will produce the following output

 ]# go run exec.go
 ;; Truncated, retrying in TCP mode.

 ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.23.rc1.el6_5.1 <<>> any google.com
 ;; global options: +cmd
 ;; Got answer:
 ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 52756
 ;; flags: qr rd ra; QUERY: 1, ANSWER: 24, AUTHORITY: 0, ADDITIONAL: 0

 ;google.com. IN ANY

 google.com. 213 IN A
 google.com. 213 IN A
 google.com. 213 IN A
 google.com. 213 IN A
 google.com. 213 IN A
 google.com. 213 IN A
 google.com. 213 IN A
 google.com. 213 IN A
 google.com. 213 IN A
 google.com. 213 IN A
 google.com. 213 IN A
 google.com. 213 IN AAAA 2607:f8b0:4006:808::1007
 google.com. 513 IN MX 50 alt4.aspmx.l.google.com.
 google.com. 21513 IN SOA ns1.google.com. dns-admin.google.com. 2014021800 7200 1800 1209600 300
 google.com. 3513 IN TXT "v=spf1 include:_spf.google.com ip4: ip4: ~all"
 google.com. 513 IN MX 30 alt2.aspmx.l.google.com.
 google.com. 21513 IN NS ns4.google.com.
 google.com. 21513 IN NS ns2.google.com.
 google.com. 21513 IN NS ns3.google.com.
 google.com. 513 IN MX 10 aspmx.l.google.com.
 google.com. 21513 IN TYPE257 \# 19 0005697373756573796D616E7465632E636F6D
 google.com. 513 IN MX 20 alt1.aspmx.l.google.com.
 google.com. 513 IN MX 40 alt3.aspmx.l.google.com.
 google.com. 21513 IN NS ns1.google.com.

 ;; Query time: 21 msec
 ;; WHEN: Tue May 13 04:43:46 2014
 ;; MSG SIZE  rcvd: 577

You can change the following code

 cmd := exec.Command("dig","any","google.com")


 application_name = "dig"
 arg_0 = "any"
 arg_1 = "google.com"

 cmd := exec.Command(application_name,arg_0,arg_1)

for readability purpose. Also, arguments must be separated in this manner instead of lumping everything into a string. Hope this tutorial will help you in learning more about Golang.


OS Package

By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.