"exit status 2" after running external command

176 Views Asked by At

Following answer, below is the code to run external command:

package main

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

func main() {
    path, err := exec.LookPath("ls")
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("pwd can be found at path: %s \n", path)

    cmd := exec.Command(path, " -l .")
    var out bytes.Buffer
    cmd.Stdout = &out

    err = cmd.Run()
    if err != nil {
        log.Println("after running external command: ", err)
    }

    log.Println("buffer output:", out.String())
}

Below is the output:

2023/10/22 10:45:03 ls can be found at path: /usr/bin/ls 
2023/10/22 10:45:03 after running external command:  exit status 2
2023/10/22 10:45:03 buffer output: 

How to run external commands using exec package?

1

There are 1 best solutions below

0
Sash Sinha On BEST ANSWER

Couple of issues:

  • In exec.Command(path, " -l ."), the arguments should be separate strings, not a single string.
  • (nit) The ls command path is logged as "pwd" which is not congruent with the output you mentioned you were getting in the question.

Try this:

package main

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

func main() {
    path, err := exec.LookPath("ls")
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("ls can be found at path: %s \n", path)

    cmd := exec.Command(path, "-l", ".")
    var out bytes.Buffer
    cmd.Stdout = &out

    err = cmd.Run()
    if err != nil {
        log.Println("after running external command: ", err)
    }

    log.Println("buffer output:", out.String())
}