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
", 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?
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.
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
", out)
The output:
The date is Fri 25/10/2013