3
package main

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

func main() {
    out, err := exec.Command("date").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("The date is %s\n", out)
}

This is a code example from the documentation for executing system commands. http://golang.org/pkg/os/exec/#example_Cmd_Output Even on the documentation site the example execute box doesn't run and has the same error: 2009/11/10 23:00:00 exec: "date": executable file not found in $PATH

On Windows I get: exec: "date": executable file not found in %PATH%

How do I get commands to work? Do I need to set a path or write out the full path of the command?

ApocSama
  • 115
  • 7
  • If you open up a terminal and run `date`, does it work? – Christian Ternus Oct 25 '13 at 00:47
  • Yes. I get 25 October 2013 01:48:31. – ApocSama Oct 25 '13 at 00:48
  • 2
    Try running `which date`, then replacing `date` in your code with the fully qualified path of the `date` executable. (I realize this isn't what you want long-term, I'm just trying to diagnose.) – Christian Ternus Oct 25 '13 at 00:51
  • Using the Get-Command to find the path, I tried `Get-Command ping` and it returned the path, `Get-Command ipconfig` did too, yet the `Get-Command date` says "The term 'date' is not recognized as the name of a cmdlet". Edit: using `where`, I get the same result. – ApocSama Oct 25 '13 at 01:11
  • 1
    On Windows 'date' is built into the command processor, so its not an executable that you are able to run. – miltonb Oct 25 '13 at 01:19

2 Answers2

4

Sadly, that example isn't going to work for you unless you get a date.exe from somewhere (Cygwin?) and put in on your %PATH%.

What's going on, I believe, is that date is a builtin in Powershell. It works for you because your shell is interpreting it.

You may be able to do

out, err := exec.Command("cmd", "/C", "date").Output()

as suggested here; I don't know, I don't have a Windows machine handy.


Sidenote:

Get-Command date says "The term 'date' is not recognized as the name of a cmdlet"

There are exactly two Google results for that phrase. One of them leads me to this, which helped me figure this out.

Community
  • 1
  • 1
Christian Ternus
  • 8,406
  • 24
  • 39
2

On windows since date is not a executable, I changed your code to run as follows:

out, err := exec.Command("cmd.exe", " /c date /t").Output()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("The date is %s\n", out)

The output:

The date is Fri 25/10/2013
miltonb
  • 6,905
  • 8
  • 45
  • 55