Home > Mobile >  Exit stauts 1 in golang
Exit stauts 1 in golang

Time:10-28

Got this simple function that throws and error with exit status 1 without any further hints to why this is happening

func execute_this(cmd string ) string {
    out, err := exec.Command("cmd","/C", cmd).Output()
    if err != nil {
        log.Fatal(err)
        fmt.Println(out)

    }
    fmt.Println(string(out))
    return string(out)
}

func main() {

        var cmd string 
        var result string 
        cmd = "pwd"
        
        

        result = execute_this(cmd)

        fmt.Println(result)
}

throw error message

2021/10/27 01:12:06 exit status 1
exit status 1

The goal is to write a function that executes system commands in shell and returning the output as a string

CodePudding user response:

Try this, it will allow you to also see the output sent to the stderr. Details here.

Specifically, in your case, the problem is that

'pwd' is not recognized as an internal or external command,
operable program or batch file.
package main

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

func execute_this(cmd string ) string {
    c := exec.Command("cmd","/C", cmd)
    c.Stderr = os.Stderr
    
    out, err := c.Output()
    if err != nil {
        log.Fatal(err)
    }
    return string(out)
}

func main() {
    cmd := "pwd"
        
    result := execute_this(cmd)
    fmt.Println(result)
}
  •  Tags:  
  • go
  • Related