Easy way to run Windows command

Folks I am new to Go, excited to use it. I want to try to port some of my Perl scripts to Go for learning exercises.

I am trying to run ‘ping -c 20 8.8.8.8’ as a test example for now; however, my code is just giving me ‘exit status 1’. In addition, I want to see the output - guessing “stdout”??; however, not sure if I am doing that in the code i cobbled together from the Go documentation.


import (
  "log"
  "fmt"
  "os/exec"
)

func main() {
   c, err  := exec.Command("cmd","ping","-c 1","8.8.8.8").CombinedOutput()
   if err != nil{
    log.Fatal(err)
   } else {
    fmt.Printf("%s\n",c)
   }
}

Still learning, so I appreciate any help.

Thank you
Roman

Hi

  1. exec.Command( ) creates a command to run. But it doesn’t run it. The first argument is which program to run and all the rest is arguments to that program.
  2. CombinedOutput() runs the program and returns combined output from stdout and stderr as a byte slice and if err is something else than nil did the command end with a exit code something else than 0 or maybe your program could not find the command

Two things. If you want to have the output as a string you can easily convert it like this

s := string( c )

and I don’t think you need to use cmd to run your command. The command exists by itself so you should be able to run it like this exec.Command(“ping”,"-c 1",“8.8.8.8”)

Hi Johan,
Thank you for the help and suggestions. Learning Go has been fun and rewarding, yet difficult at times.

package main

import (
  "fmt"
  "os/exec"
)

func main() {
   c,_ := exec.Command("ping","-n","1","8.8.8.8").CombinedOutput()
   s := string(c)

    fmt.Printf("%s\n",s)

}

I updated my code with your suggestions with:

s := string( c )

However, on Windows I still needed to specify “ping” and “.CombineOutput()” in order for it to work.

Thank you again for your help.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.